题目:
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]
解题:
基本等同于Combination Sum,dfs下一层时候不是从当前坐标开始,而是从下一个开始。记录答案的时候判一下重。
代码:
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { ans.clear(); single.clear(); sort(candidates.begin(), candidates.end()); in = candidates; dfs(0, target); return ans; } private: vector<vector<int> > ans; vector<int> single, in; void dfs(int pos, int target) { if(target == 0) { bool flag = 0; for(int i = 0; i < ans.size(); i ++) { if(ans[i] == single) { flag = 1; break; } } if(!flag) ans.push_back(single); return ; } for(int i = pos; i < in.size(); i ++) { if(in[i] > target) break; single.push_back(in[i]); dfs(i + 1, target - in[i]); single.pop_back(); } return; } };