力扣216 组合总和III

和昨天的II差不多,回溯+剪枝,判断一下个数就好

力扣216 组合总和III_第1张图片

class Solution {
public:
    vector> combinationSum3(int k, int n) {
        vectornum = {1,2,3,4,5,6,7,8,9};
        vector>res;
        if(n < 0 || k <= 0)
        {
            return res;
        }
        vectortmp;
        dfs(k, n, num, 0,0, tmp, res);
        return res;
    }
    void dfs(int k, int n, vector& num, int start, int sum, vector& tmp, vector>& res)
    {
        if(sum == n && tmp.size() == k)
        {
            res.push_back(tmp);
            return;
        }
        if(sum > n)
        {
            sum = sum - tmp.front();
            return;
        }
        for(int i = start; i < 9; i++)
        {
            tmp.push_back(num[i]);
            dfs(k,n,num,i+1,sum+num[i],tmp,res);
            tmp.pop_back();
        }
    }
};

 力扣216 组合总和III_第2张图片

 

你可能感兴趣的:(#,回溯)