和上一题差不多
class Solution { public: void search(vector<vector<int> >& ans , vector<int>& tmp ,vector<int> &candidates , int target , int sum , int start) { if(sum > target) return; if(sum == target) { ans.push_back(tmp); return ; } int prev = -1; for(int i = start ; i < candidates.size() ; i++) { if(prev == candidates[i]) continue; prev = candidates[i]; tmp.push_back(candidates[i]); search(ans,tmp,candidates,target,sum+candidates[i] , i+1); tmp.pop_back(); } } vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { vector<vector<int> > ans; vector<int> tmp; sort(candidates.begin() , candidates.end()); search(ans,tmp,candidates,target, 0 , 0); return ans; } };
by 1957