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] ]
Subscribe to see which companies asked this question
c++ code:
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> combs; vector<int> comb; sort(candidates.begin(),candidates.end()); // 排序或将candidates中数去重 combinationSum2(combs,comb,candidates,0,target); return combs; } // 自定义函数 void combinationSum2(vector<vector<int>>& combs, vector<int>& comb, vector<int>& candidates, int start, int target) { if (target < 0) return; else if(target==0) { combs.push_back(comb); return; } for(int i=start;i<candidates.size();i++) { if(i>start && candidates[i-1]==candidates[i]) continue; comb.push_back(candidates[i]); combinationSum2(combs,comb,candidates,i+1,target-candidates[i]); comb.pop_back(); } } };