39. Combination Sum
題目: 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.
- 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]
]
分析: 采用回溯法, 在每一次的遞歸中把剩下的元素分別加入到結(jié)果結(jié)合中, 并把target
減去加入的數(shù), 然后把剩下的元素放到下一層的遞歸中去解決. 代碼在實現(xiàn)的過程中要注意重復元素的判斷.
code:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ret;
vector<int> tmp;
helper(candidates, 0, target, tmp, ret);
return ret;
}
void helper(vector<int>& candidates, int begin, int target, vector<int>& tmp, vector<vector<int>>& ret) {
if(target < 0)
return;
if(target == 0)
ret.push_back(tmp);
for(int i = begin; i < candidates.size(); ++i) {
if(i > 0 && candidates[i] == candidates[i-1])
continue;
tmp.push_back(candidates[i]);
helper(candidates, i, target-candidates[i], tmp, ret);
tmp.pop_back();
}
}
};