Combination Sum II
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]
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &num, int target) { int n = num.size(); sort(num.begin(), num.end()); vector<int> solve; ans.clear(); iter(0, n, solve, 0, target, num); return ans; } void iter(int ind, int n, vector<int> solve, int sum, int target, vector<int> &candidates){ if(sum == target){ ans.push_back(solve); return; } if(ind==n) return; if(candidates[ind] > target) return; int newsum = sum+candidates[ind]; if(sum > target) return; int index = ind; while(candidates[index] == candidates[index + 1]){index++;} iter(index+1, n, solve, sum, target, candidates); solve.push_back(candidates[ind]); iter(ind+1, n, solve, newsum, target, candidates); } vector<vector<int> > ans; };
浙公网安备 33010602011771号