|
9 | 9 | * Find all possible combinations of k numbers that add up to a number n,
|
10 | 10 | * given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
|
11 | 11 |
|
12 |
| -
|
13 | 12 | Example 1:
|
14 |
| -
|
15 | 13 | Input: k = 3, n = 7
|
16 |
| -
|
17 |
| - Output: |
18 |
| -
|
19 |
| - [[1,2,4]] |
| 14 | + Output: [[1,2,4]] |
20 | 15 |
|
21 | 16 | Example 2:
|
22 |
| -
|
23 | 17 | Input: k = 3, n = 9
|
24 |
| -
|
25 |
| - Output: |
26 |
| -
|
27 |
| - [[1,2,6], [1,3,5], [2,3,4]]*/ |
| 18 | + Output: [[1,2,6], [1,3,5], [2,3,4]] |
| 19 | + */ |
28 | 20 | public class _216 {
|
29 | 21 |
|
30 |
| - public List<List<Integer>> combinationSum3(int k, int n) { |
31 |
| - List<List<Integer>> result = new ArrayList(); |
32 |
| - int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; |
33 |
| - backtracking(k, n, nums, 0, new ArrayList(), result); |
34 |
| - return result; |
35 |
| - } |
| 22 | + public static class Solution1 { |
| 23 | + public List<List<Integer>> combinationSum3(int k, int n) { |
| 24 | + List<List<Integer>> result = new ArrayList(); |
| 25 | + int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; |
| 26 | + backtracking(k, n, nums, 0, new ArrayList(), result); |
| 27 | + return result; |
| 28 | + } |
36 | 29 |
|
37 |
| - void backtracking(int k, int n, int[] nums, int start, List<Integer> curr, List<List<Integer>> result) { |
38 |
| - if (n > 0) { |
39 |
| - for (int i = start; i < nums.length; i++) { |
40 |
| - curr.add(nums[i]); |
41 |
| - backtracking(k, n - nums[i], nums, i + 1, curr, result); |
42 |
| - curr.remove(curr.size() - 1); |
| 30 | + void backtracking(int k, int n, int[] nums, int start, List<Integer> curr, List<List<Integer>> result) { |
| 31 | + if (n > 0) { |
| 32 | + for (int i = start; i < nums.length; i++) { |
| 33 | + curr.add(nums[i]); |
| 34 | + backtracking(k, n - nums[i], nums, i + 1, curr, result); |
| 35 | + curr.remove(curr.size() - 1); |
| 36 | + } |
| 37 | + } else if (n == 0 && curr.size() == k) { |
| 38 | + result.add(new ArrayList(curr)); |
43 | 39 | }
|
44 |
| - } else if (n == 0 && curr.size() == k) { |
45 |
| - result.add(new ArrayList(curr)); |
46 | 40 | }
|
47 | 41 | }
|
48 | 42 | }
|
0 commit comments