Skip to content

Commit 6e4b7ed

Browse files
refactor 40
1 parent 459b755 commit 6e4b7ed

File tree

1 file changed

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

1 file changed

+19
-36
lines changed

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

Lines changed: 19 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,48 +3,31 @@
33
import java.util.ArrayList;
44
import java.util.Arrays;
55
import java.util.List;
6-
/**
7-
* 40. Combination Sum II
8-
*
9-
* Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
10-
* Each number in C may only be used once in the combination.
116

12-
Note:
13-
All numbers (including target) will be positive integers.
14-
The solution set must not contain duplicate combinations.
15-
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
16-
A solution set is:
17-
[
18-
[1, 7],
19-
[1, 2, 5],
20-
[2, 6],
21-
[1, 1, 6]
22-
]
23-
*/
247
public class _40 {
258

269
public static class Solution1 {
27-
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
28-
List<List<Integer>> result = new ArrayList();
29-
Arrays.sort(candidates);
30-
backtracking(candidates, 0, result, target, new ArrayList());
31-
return result;
32-
}
10+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
11+
List<List<Integer>> result = new ArrayList();
12+
Arrays.sort(candidates);
13+
backtracking(candidates, 0, result, target, new ArrayList());
14+
return result;
15+
}
3316

34-
void backtracking(int[] candidates, int start, List<List<Integer>> result, int target,
35-
List<Integer> curr) {
36-
if (target > 0) {
37-
for (int i = start; i < candidates.length; i++) {
38-
if (candidates[i] > target || (i > start && candidates[i - 1] == candidates[i])) {
39-
continue;
17+
void backtracking(int[] candidates, int start, List<List<Integer>> result, int target,
18+
List<Integer> curr) {
19+
if (target > 0) {
20+
for (int i = start; i < candidates.length; i++) {
21+
if (candidates[i] > target || (i > start && candidates[i - 1] == candidates[i])) {
22+
continue;
23+
}
24+
curr.add(candidates[i]);
25+
backtracking(candidates, i + 1, result, target - candidates[i], curr);
26+
curr.remove(curr.size() - 1);
27+
}
28+
} else if (target == 0) {
29+
result.add(new ArrayList(curr));
4030
}
41-
curr.add(candidates[i]);
42-
backtracking(candidates, i + 1, result, target - candidates[i], curr);
43-
curr.remove(curr.size() - 1);
44-
}
45-
} else if (target == 0) {
46-
result.add(new ArrayList(curr));
4731
}
48-
}
4932
}
5033
}

0 commit comments

Comments
 (0)