关闭

leetcode 40: Combination Sum II

75人阅读 评论(0) 收藏 举报
分类:
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int> > res;
        vector<int> set;
        sort(candidates.begin(),candidates.end());
        helper(candidates,0,target,set,res);
        return res;
    }
    void helper(vector<int>& candidates,int idx,int target,vector<int>& set,vector<vector<int> >& res){
        for(int i=idx;i<candidates.size()&&candidates[i]<=target;i++)
        {
            if(i==idx||candidates[i]!=candidates[i-1])//The cases with repeat numbers are considered in the recursion, so they should not be considered in the loop
            {
                set.push_back(candidates[i]);
                if(candidates[i]==target)
                {
                    res.push_back(set);
                    set.pop_back();
                    break;
                }
                else
                {
                    helper(candidates,i+1,target-candidates[i],set,res);
                    set.pop_back();
                }
            }
        }
    }
};

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21894次
    • 积分:2007
    • 等级:
    • 排名:千里之外
    • 原创:186篇
    • 转载:16篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论