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:
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] ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution {public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> results; sort(candidates.begin(), candidates.end()); helper(results, vector<int>{}, candidates, target, 0); return results; } void helper(vector<vector<int>> &results, vector<int> result, vector<int>& c, int target, int index) { for (int i = index; i < c.size(); ++i) { int t = target - c[i]; if (t < 0) { return; } else if(i==index || c[i] != c[i - 1]){ // jump over duplicate results result.push_back(c[i]); if (t == 0) { results.push_back(result); } else { helper(results, result, c, t, i + 1);// i + 1: insure every element is used once } result.pop_back(); } } }}; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution {public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> results; sort(candidates.begin(), candidates.end()); helper(results, vector<int>{}, candidates, target, 0); return results; } void helper(vector<vector<int>> &results, vector<int> result, vector<int>& c, int target, int index) { if( target == 0){ results.push_back(result); return; } for (int i = index; i < c.size() && target >= c[i]; ++i) { if(i==index || c[i] != c[i - 1]){ // jump over duplicate results result.push_back(c[i]); helper(results, result, c, target - c[i], i + 1);// i + 1: insure every element is used once result.pop_back(); } } }}; |
原文:http://www.cnblogs.com/zhxshseu/p/079f1208560c9124fe6ad19b4017ed20.html