Combination Sum III

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.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

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

Solution

Basically the same idea as Combination I, II. The difference is that the given candidates is now 1, 2, ..., 9 for each position in the combination, and the constraints is the number of numbers in the combination. So there's similarities with Combinations too.

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();

        comboHelper(1, n, k, new ArrayList<Integer>(), ans);

        return ans;
    }

    private void comboHelper(int start, int remain, int k, List<Integer> combo, List<List<Integer>> ans) {
        if (remain == 0) {
            if (combo.size() == k) {
                ans.add(new ArrayList<Integer>(combo));
            }
            return;
        }

        for (int i = start; i <= 9; i++) {
            combo.add(i);
            comboHelper(i + 1, remain - i, k, combo, ans);
            combo.remove(combo.size() - 1);
        }
    }
}

Reference

https://leetcode.com/problems/combination-sum-ii/discuss/16878/Combination-Sum-I-II-and-III-Java-solution-\(see-the-similarities-yourself\)

results matching ""

    No results matching ""