题目描述
- 题目中所有的数字(包括目标数T)都是正整数
- 组合中的数字 (a 1, a 2, … , a k) 要按非递增排序 (ie, a 1 ≤ a 2 ≤ … ≤ a k).
- 结果中不能包含重复的组合
[1, 2, 5]
[2, 6]
[1, 1, 6]
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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
- The solution set must not contain duplicate combinations.
For example, given candidate set10,1,2,7,6,1,5and target8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
class Solution {
vector< int> d;
vector <vector <int>> z;
set<vector<int>> s;
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(),num.end());
dfs(num,0,target,0);
set<vector<int>> ::iterator it;
for (it=s.begin();it!=s.end();z.push_back(*it),it++);
return z;
}
void dfs(vector<int> & candidates,int x ,int t, int step){
if (x>t || x<0 ) return ;
if (x==t){s.insert(d);}
else
{
int i;
for (i=step;i<candidates.size();i++){
d.push_back(candidates[i]);
dfs(candidates,x+candidates[i],t,i+1);
d.pop_back();
}
}
}
};