216. 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]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

因为自己不太擅长写递归的题目,一般题目都要纠结很久。
这个题目几分钟写完,一次AC,感觉还是很开心的啊!

class Solution {
public:
    void find(vector<vector<int>> &v,int j,int k,int n,vector<int> &num){
        if(k==0){
            if(n==0)
                v.push_back(num);
            return;
        }
        for(int i=j+1;i<=9;i++){
            if(n>=i){
                num.push_back(i);
                find(v,i,k-1,n-i,num);
                num.pop_back();
            }
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> v;
        vector<int>num;
        find(v,0,k,n,num);
        return v;
    }
};

你可能感兴趣的:(216. Combination Sum III)