[LeetCode] 216. 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]]
组合总和III。需要先做过39题和40题。题意是给两个参数K和N,请返回一个集合,集合包含的所有子集满足K个数字的加和是N。组合中只允许包含1 - 9的正整数,并且每种组合中不允许有重复数字。
这道题跟前两个版本的区别在于多了一个参数K,因为题目规定每个子集里数字的个数一定要为K而且他们的sum还得是n。既然子集里面不能有重复的数字,所以start那个参数在递归到下一层的时候需要 + 1。其余的部分就比较常规了。
时间O(2^n)
空间O(n)
Java实现
1 class Solution { 2 public List<List<Integer>> combinationSum3(int k, int n) { 3 List<List<Integer>> res = new ArrayList<>(); 4 helper(res, new ArrayList<>(), n, k, 1); 5 return res; 6 } 7 8 private void helper(List<List<Integer>> res, List<Integer> list, int n, int k, int start) { 9 // when to return 10 if (k == 0 && n == 0) { 11 res.add(new ArrayList<>(list)); 12 return; 13 } 14 for (int i = start; i <= 9; i++) { 15 list.add(i); 16 helper(res, list, n - i, k - 1, i + 1); 17 list.remove(list.size() - 1); 18 } 19 } 20 }