关闭

39. Combination Sum

38人阅读 评论(0) 收藏 举报
分类:

回溯

class Solution {
public:
    void Getans(vector<int>& nums,int sta,vector<vector<int>>& res,int cur,vector<int> ans,int target)
    {
        if(cur==target&&ans.size()>0)
        {
            res.push_back(ans);
            return;
        }
        if(nums[sta]>target||nums[sta]+cur>target||sta>=nums.size())
            return;
        
        Getans(nums,sta+1,res,cur,ans,target);
        ans.push_back(nums[sta]);
        Getans(nums,sta,res,cur+nums[sta],ans,target);
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        int n=candidates.size();
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> res;
        vector<int> ans;
        Getans(candidates,0,res,0,ans,target);
        return res;
    }
};

update:

class Solution {
public:
    void Getans(vector<int>& nums,int sta,vector<vector<int>>& res,int cur,vector<int> ans,int target)
    {
        if(cur==target&&ans.size()>0)
        {
            res.push_back(ans);
            return;
        }
        if(cur>target)
            return;
        for(int i=sta;i<nums.size();i++)
        {
            ans.push_back(nums[i]);
            Getans(nums,i,res,cur+nums[i],ans,target);   
            ans.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        int n=candidates.size();
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> res;
        vector<int> ans;
        Getans(candidates,0,res,0,ans,target);
        return res;
    }
};


0
0

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