裸的dfs
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 ; } for(int i = start ; i < candidates.size() ; i++) { tmp.push_back(candidates[i]); search(ans,tmp,candidates,target,sum+candidates[i] , i); tmp.pop_back(); } } vector<vector<int> > combinationSum(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