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]
]
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
//sort(candidates.begin(), candidates.end());
vector<int> sol;
vector<vector<int>> res;
dfs(candidates, target, 0, sol, res);
return res;
}
private:
void dfs(vector<int> &arr, int target, int level,vector<int> &sum, vector<vector<int>>& ret){
if(target == 0){
ret.push_back(sum);
return;
}
for(int i = level; i< arr.size(); i++){
if(arr[i] <= target){
sum.push_back(arr[i]);
dfs(arr, target - arr[i], i, sum, ret);
sum.pop_back();
}
}
}
};
40.Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
注意这道题目与上面的区别是给出的数据集合可能有重复的值
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> sum;
dfs(candidates, target, 0, sum, res);
sort(res.begin(), res.end());
auto it = unique(res.begin(), res.end());
res.erase(it, res.end());
return res;
}
private:
void dfs(vector<int> &arr, int left, int level, vector<int>& sol, vector<vector<int>> &ret){
if(left == 0){
sort(sol.begin(), sol.end());
ret.push_back(sol);
return;
}
for(int i = level; i < arr.size(); i++){
if(left >= arr[i]){
sol.push_back(arr[i]);
dfs(arr, left - arr[i], i + 1, sol, ret);
sol.pop_back();
}
}
}
};