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;
}
};