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]
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &num, int target) { sort(num.begin(), num.end()); vector<vector<int>> res; vector<int> path; dfs(res, path, num, target, 0); return res; } void dfs(vector<vector<int>> &res, vector<int> &path, vector<int> &num, int target, int idx) { if(target < 0) return; if(target == 0) { res.push_back(path); return; } for(int i = idx; i < num.size(); i++) { path.push_back(num[i]); dfs(res, path, num, target - num[i], i+1); path.pop_back(); while(i < num.size() - 1 && num[i] == num[i+1]) i++; } } };