Leetcode 216. 组合总和 III

暴力枚举配合剪枝

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> tmp;
    void dfs(int k,int n){
        int i= tmp.empty()? 0:tmp.back();
        ++i;
        if(i+k-1>9 || (19-k)*k/22*i+k-1)*k/2>n) return;
        if(k==1){
            tmp.push_back(n);
            ans.push_back(tmp);
            tmp.pop_back();
            return ;
        }
        for(;i<=9;++i)
            tmp.push_back(i),dfs(k-1,n-i),tmp.pop_back();
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        dfs(k,n);
        return ans;
    }
};

你可能感兴趣的:(Leetcode 216. 组合总和 III)