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 is used once in the combination.
Note:
- All numbers (including target) would be positive integers.
- elements in a combination (a 1 , a 2 , ..., a k ) must is 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,5
and target8
,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Test instructions: Or the same as the previous one, the number of combinations, but there is one condition is: Each number can only be used once, can not repeat the result set
Idea: A little change on the line, one is every time the subscript is +1, the other is to avoid repetition, skip the same number
Class Solution {public: void Dfs (vector<int> candidates, int index, int sum, int target, vector<vector<in T>> &res, vector<int> &path) { if (sum > Target) return; if (sum = = target) { res.push_back (path); return; } for (int i = index; i < candidates.size (); i++) { path.push_back (candidates[i]); DFS (candidates, i+1, Sum+candidates[i], target, res, path); Path.pop_back (); while (I < candidates.size ()-1 && candidates[i] = = candidates[i+1]) i++; } } vector<vector<int> > CombinationSum2 (vector<int> &candidates, int target) { sort ( Candidates.begin (), Candidates.end ()); vector<vector<int> > Res; vector<int> path; DFS (candidates, 0, 0, Target, res, path); return res; }};
Leetcode Combination Sum II