1957

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

[leetcode]Combination Sum II

Posted on 2014-01-10 13:40  1957  阅读(121)  评论(0编辑  收藏  举报

和上一题差不多

 

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