Problem
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
A solution set is:
10,1,2,7,6,1,5
and target 8
, A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Code
void DFS_cs2(int pos,int k,int target,const vector<int> &num, vector<int> &out,vector<vector<int> > &result) { if(target == 0){ result.push_back(vector<int>(out.begin(),out.begin() + pos)); return; } if(target < 0) return; if(pos == out.size()) out.resize(2*pos + 1); for(int i = k;i < num.size();++i){ if(i != 0 && i != k && num[i] == num[i - 1]) continue; out[pos] = num[i]; DFS_cs2(pos + 1,i + 1,target - num[i],num,out,result); } } vector<vector<int> > combinationSum2(vector<int> &num, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int> >result; vector<int> out; sort(num.begin(),num.end()); DFS_cs2(0,0,target,num,out,result); return result; }
No comments:
Post a Comment