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 (a1, a2, … , 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:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> path;
sort(candidates.begin(),candidates.end());
check(candidates,target,0,0,path, result);
return result;
}
void check(vector<int>& candidates, int target, int sum, int num, vector<int>& path, vector<vector<int>>& result){
//sum是当前的加和;num是记录当前加的数字的下标,去除重复的结果;path是记录加过的数字;
if(sum>target) return;
else if(sum==target)
result.push_back(path);
else{
for(int i=num;i<candidates.size();i++){
path.push_back(candidates[i]);
check(candidates,target,sum+candidates[i],i,path,result);
path.pop_back();
}
}
}
};
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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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]
相对于上一道题目,这个题要求用不同的元素来组合target。我们需要做两方面的修改。num的值每次递归要+1,即从下一个位置查找可能的结果。此时,如果数组中存在值相等的元素,我们要处理结果重复的情况。屡一下思路,检查重复的时候只需要在回溯的时候检查就可以了,在调用pop_back()之后,如果下一个要加入的值和当前值是一样的,那后续的结果肯定也是一样的,所以,只要在这个位置过滤掉值相同的元素就可以了,代码如下:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> result;
vector<int> path;
check(candidates,target,0,0,path,result);
return result;
}
void check(vector<int>& candidates, int target, int sum, int num, vector<int>& path, vector<vector<int>>& result){
if(sum>target) return;
else if(sum==target)
result.push_back(path);
else{
for(int i=num;i<candidates.size();i++){
path.push_back(candidates[i]);
check(candidates,target,sum+candidates[i],i+1,path,result); //从下一个位置开始查找
path.pop_back();
while(i<candidates.size() && candidates[i]==candidates[i+1]) //去除重复元素
i++;
}
}
}
};