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]
Have you met this question in a real interview?
Yes
No
回溯法,唯一注意的是,1,1,1 target=2的话,会产生重复数据。
去重的判断条件是
1、如果i和i-1相等,则只有i-1加入到了求和的集合中才能将i算入 ,如果i-1没加入,则说明之前某一组肯定把i-1节点加入了,这里如果加入i节点,则会和加入i-1节点的重复!!!注意0节点就okay~
2、如果不相等,正常处理
class Solution {
vector<bool> flag;
vector<vector<int> > ret;
void dfs(vector<int> &num, int curDep, int maxDep, int sum, int target){
if(sum==target){
vector<int> ans;
for(int i=0;i<num.size();i++)
if(flag[i])
ans.push_back(num[i]);
ret.push_back(ans);
return;
}
if(sum>target||curDep==maxDep)
return;
if((curDep==0)||(curDep!=0&&( (num[curDep]==num[curDep-1]&&flag[curDep-1]) || (num[curDep]!=num[curDep-1]) ) ) ){
flag[curDep]=true;
dfs(num,curDep+1, maxDep, sum+num[curDep], target);
}
flag[curDep]=false;
dfs(num,curDep+1, maxDep, sum, target);
}
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(),num.end());
for(int i=0;i<num.size();i++)
flag.push_back(false);
dfs(num, 0, num.size(), 0, target);
return ret;
}
};