216 Combination Sum III

1. Question

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

2. Implementation

(1) Backtracking

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> combinations = new ArrayList<>();
        getCombinations(1, 0, k, n, combinations, res);
        return res;
    }

    public void getCombinations(int start, int sum, int k, int target, List<Integer> combinations, List<List<Integer>> res) {
        if (sum > target) {
            return;
        }

        if (k == 0 && sum == target) {
            res.add(new ArrayList<>(combinations));
            return;
        }

        for (int i = start; i <= 9; i++) {
            combinations.add(i);
            getCombinations(i + 1, sum + i, k - 1, target, combinations, res);
            combinations.remove(combinations.size() - 1);
        }
    }
}

3. Time & Space Complexity

Backtracking: 时间复杂度O(n^k), 根据组合公式得到,空间复杂度O(n^k)

Last updated