1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Combination Sum

Posted on 2014-01-10 11:24  1957  阅读(136)  评论(0编辑  收藏  举报

裸的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;
    }
};