Leecode 39. 组合总和 dfs+回溯+剪枝

原题链接:Leecode 39. 组合总和 dfs+回溯+剪枝
Leecode 39. 组合总和 dfs+回溯+剪枝_第1张图片
Leecode 39. 组合总和 dfs+回溯+剪枝_第2张图片

class Solution {
public:
    vector<int> tmp;
    vector<vector<int>> res;
    void dfs(vector<int>& candidates, int target,int now)
    {
        if(target==0)
        {
            res.push_back(tmp);
            return ;
        }
        if(target<candidates[0])
            return ;
        for(int i=now;i<candidates.size();i++)
        {
            if(target<candidates[i])
                break;
            else 
            {
                tmp.push_back(candidates[i]);
                dfs(candidates,target-candidates[i],i);
                tmp.pop_back();
            }
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        if(target<candidates[0])
           return res;
        dfs(candidates,target,0);
        return res;
    }
};

你可能感兴趣的:(Leetcode,c++,leetcode,dfs,深度优先)