Skip to content

Commit f41c375

Browse files
refactor 216
1 parent c731340 commit f41c375

File tree

1 file changed

+19
-25
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+19
-25
lines changed

src/main/java/com/fishercoder/solutions/_216.java

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -9,40 +9,34 @@
99
* Find all possible combinations of k numbers that add up to a number n,
1010
* given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
1111
12-
1312
Example 1:
14-
1513
Input: k = 3, n = 7
16-
17-
Output:
18-
19-
[[1,2,4]]
14+
Output: [[1,2,4]]
2015
2116
Example 2:
22-
2317
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+
*/
2820
public class _216 {
2921

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+
}
3629

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));
4339
}
44-
} else if (n == 0 && curr.size() == k) {
45-
result.add(new ArrayList(curr));
4640
}
4741
}
4842
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy