Likou 216. Combination Sum III

topic:

Find all the combinations of k numbers that add up to n. Only positive integers from 1 to 9 are allowed in the combination, and there are no repeated numbers in each combination.

Example:

Input: k = 3, n = 7
Output: [[1,2,4]]

solution

sum records the current sum, which can be added in the function call, which can save a step of backtracking.

Optimizing pruning: When the number does not reach the limit, the sum is greater than the target and time.

if (sum > n) return;

Code

class Solution {
    
    
private:
    vector<int> path;
    vector<vector<int>> res;
public:
    void traversal(int k, int n, int sum, int Index) {
    
    
        if (path.size() == k) {
    
    
            if (sum == n)
                res.push_back(path);
                return;
        }
        for (int i = Index; i <= 9; i++) {
    
    
            path.push_back(i);
            traversal(k, n, sum + i, i + 1);
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
    
    
        path.clear();
        res.clear();
        traversal(k, n, 0, 1);
        return res;
    }
};

Guess you like

Origin blog.csdn.net/Matcha_/article/details/114109721