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 29 30 31 32
| class Solution { public: vector<vector<int>> res; void dfs(vector<int>& candidates,vector<int>& ans,int sum,int pos, int &target){ ans.push_back(candidates[pos]); if(sum+candidates[pos]==target) res.push_back(ans); else if(sum+candidates[pos]<target){ for(int i=pos+1;i<candidates.size();i++){ if(i>pos+1 && candidates[i]==candidates[i-1]) continue; dfs(candidates,ans,sum+candidates[pos],i,target); } } ans.pop_back(); return ; }
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(),candidates.end()); vector<int> ans; for(int i=0;i<candidates.size();i++){ if(i>0 && candidates[i]==candidates[i-1]) continue; dfs(candidates,ans,0,i,target); } return res; } };
|