[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,因为题目规定每个子集里数字的个数一定要为K而且他们的sum还得是n。既然子集里面不能有重复的数字,所以start那个参数在递归到下一层的时候需要 + 1。其余的部分就比较常规了。

时间O(2^n)

空间O(n)

Java实现

 1 class Solution {
 2     public List> combinationSum3(int k, int n) {
 3         List> res = new ArrayList<>();
 4         helper(res, new ArrayList<>(), n, k, 1);
 5         return res;
 6     }
 7 
 8     private void helper(List> res, List 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 }

 

LeetCode 题目总结

你可能感兴趣的:([LeetCode] 216. Combination Sum III)