Problem

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

思路

    /*
        k elements to meet n
        pick 1, k - 1 elements to meet n - 1
        pick 2, k - 2 elements to meet n - 2
        pick 3, k - 3 elements to meet n - 3
        ...
        ...
        ...
    */
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        if (k <= 0) return result;

        helper(result, new ArrayList<Integer>(), k, n, 1);
        return result;
    }

    private void helper(List<List<Integer>> result, List<Integer> path, int k, int target, int start) {
        for (int i = start; i <= 9; i++) {
            path.add(i);
            target -= i;

            if (k - 1 == 0 && target == 0) {
                result.add(new ArrayList<Integer>(path));
            }

            if (k - 1 > 0 && target > 0) {
                helper(result, path, k - 1, target, i + 1);
            }

            target += i;
            path.remove(path.size() - 1);
        }
    }

results matching ""

    No results matching ""