216. Combination Sum III

Description

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.

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Solution

注意,在每种组合中,每个数字只能用一次。

DFS

简单的题,传入pre即可。

class Solution {
    public List> combinationSum3(int k, int n) {
        List> combinationSums = new ArrayList<>();
        if (k < 1 || n < k || n > 9 * k) {
            return combinationSums;
        }
        
        combinationSumRecur(0, k, n, new ArrayList<>(), combinationSums);
        return combinationSums;
    }
    
    public void combinationSumRecur(int pre, int k, int n
                                   , List combinationSum
                                   , List> combinationSums) {
        if (k == 0 && n == 0) {
            combinationSums.add(new ArrayList<>(combinationSum));
            return;
        }
        
        if (pre >= 9 || k < 1 || n < 0) {
            return;
        }
        
        for (int i = pre + 1; i <= Math.min(9, n); ++i) {
            combinationSum.add(i);
            combinationSumRecur(i, k - 1, n - i, combinationSum, combinationSums);
            combinationSum.remove(combinationSum.size() - 1);
        }
    }
}

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