[LeetCode]Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


DFS+剪枝,注意顺序是递增的。且最大不会大于9.

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> ret;
        vector<vector<int>> ans;
        dfs(ans,ret,0,k,n);
        return ans;
    }
    
    void dfs(vector<vector<int>> &ans,vector<int> &ret,int start,int k,int n){
        if(n<((2*start+k+1)*k/2) || n>((19-k)*k/2)) //剪枝加快搜索速度
            return;
        if(k==0){
            if(n==0) ans.push_back(ret);
            return ;
        }
        for(int i=start+1; i<=9; ++i){
            ret.push_back(i);
            dfs(ans,ret,i,k-1,n-i);
            ret.pop_back();
        }
    }
};


你可能感兴趣的:([LeetCode]Combination Sum III)