LEETCODE: Combination Sum

来源:互联网 发布:node js redis 编辑:程序博客网 时间:2024/06/14 16:06

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 


排好序,然后通过递归解决问题。在任何时候,当前的数和它之后的数都有可能是下一个数。


class Solution {public:    void combinationSumInternal(vector<int> &candidates, vector<int> currentnums, int current,                                 int target, int start, int end, vector<vector<int> > &results) {        if(current == target)         {            results.push_back(currentnums);            return;        }                if(current > target)            return;                for(int ii = start; ii < end; ii ++) {            currentnums.push_back(candidates[ii]);            combinationSumInternal(candidates, currentnums, current + candidates[ii], target, ii, end, results);            currentnums.pop_back();        }            }    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<vector<int> > results;        vector<int> currentnums;        sort(candidates.begin(), candidates.end());        combinationSumInternal(candidates, currentnums, 0, target, 0, candidates.size(), results);        return results;    }};





0 0
原创粉丝点击