Combination Sum III —— LeetCode

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

题目大意:从1~9找出所有的k个数的组合,使其和等于n。

解题思路:还是回溯,每个数只能出现一次,每次递归都从当前数的下一个开始,当k==0&&n==0,就可以加入结果集。

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> tmp = new ArrayDeque<>();
        if (n == 0 || k == 0 || n / k > 9) {
            return res;
        }
        helper(res, tmp, 1, k, n);
        return res;
    }

    private void helper(List<List<Integer>> res, Deque<Integer> tmp, int start, int k, int n) {
        if (0 == n && k == 0) {
            res.add(new ArrayList<>(tmp));
//            System.out.println(tmp);
            return;
        }
        for (int i = start; i <= 9; i++) {
            tmp.addLast(i);
            helper(res, tmp, i + 1, k - 1, n - i);
            tmp.removeLast();
        }
    }
原文地址:https://www.cnblogs.com/aboutblank/p/4538926.html