Skip to content

Commit be637da

Browse files
[N-0] refactor 39
1 parent 4f2e754 commit be637da

File tree

1 file changed

+18
-32
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-32
lines changed
Lines changed: 18 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.fishercoder.solutions;
22

3-
import com.fishercoder.common.utils.CommonUtils;
4-
53
import java.util.ArrayList;
64
import java.util.Arrays;
75
import java.util.List;
@@ -25,39 +23,27 @@ All numbers (including target) will be positive integers.
2523
]*/
2624
public class _39 {
2725

28-
public List<List<Integer>> combinationSum(int[] candidates, int target) {
29-
List<List<Integer>> result = new ArrayList();
30-
Arrays.sort(candidates);
31-
backtracking(candidates, target, 0, new ArrayList(), result);
32-
return result;
33-
}
26+
public static class Solution1 {
27+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
28+
List<List<Integer>> result = new ArrayList();
29+
Arrays.sort(candidates);
30+
backtracking(candidates, target, 0, new ArrayList(), result);
31+
return result;
32+
}
3433

35-
private void backtracking(int[] candidates, int target, int startIndex, List<Integer> curr, List<List<Integer>> result) {
36-
if (target > 0) {
37-
int prev = -1;
38-
for (int i = startIndex; i < candidates.length; i++) {
39-
if (candidates[i] > target) {
40-
return;//this is one very important step to optimize this algorithm: pruning
41-
}
42-
if (prev != -1 && prev == candidates[i]) {
43-
continue;
34+
void backtracking(int[] candidates, int target, int start, List<Integer> curr, List<List<Integer>> result) {
35+
if (target > 0) {
36+
for (int i = start; i < candidates.length; i++) {
37+
if (candidates[i] > target) {
38+
return;//pruning
39+
}
40+
curr.add(candidates[i]);
41+
backtracking(candidates, target - candidates[i], i, curr, result);
42+
curr.remove(curr.size() - 1);
4443
}
45-
curr.add(candidates[i]);
46-
backtracking(candidates, target - candidates[i], i, curr, result);
47-
curr.remove(curr.size() - 1);
44+
} else if (target == 0) {
45+
result.add(new ArrayList(curr));
4846
}
49-
} else if (target == 0) {
50-
result.add(new ArrayList(curr));
5147
}
5248
}
53-
54-
55-
public static void main(String... args) {
56-
_39 test = new _39();
57-
int[] candidates = new int[]{2, 3, 6, 7};
58-
int target = 7;
59-
List<List<Integer>> result = test.combinationSum(candidates, target);
60-
CommonUtils.printListList(result);
61-
}
62-
6349
}

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