Skip to content

Commit ba82a09

Browse files
committed
CombinationSumII
1 parent 8452854 commit ba82a09

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package backtracking;
2+
3+
import java.util.*;
4+
5+
// https://leetcode.com/problems/combination-sum-ii/
6+
public class CombinationSumII {
7+
8+
public static void main(String[] args) {
9+
CombinationSumII obj = new CombinationSumII();
10+
int[] candidates = {10,1,2,7,6,1,5};
11+
int target = 8;
12+
List<List<Integer>> resultList = obj.combinationSum2(candidates, target);
13+
System.out.println("resultList >> " + Arrays.toString(resultList.toArray()));
14+
}
15+
16+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
17+
List<List<Integer>> resultList = new ArrayList<>();
18+
Arrays.sort(candidates);
19+
recursive(candidates, target, resultList, new ArrayList<Integer>(), 0);
20+
21+
return resultList;
22+
}
23+
24+
public void recursive(int[] candidates, int target, List<List<Integer>> resultList, List<Integer> list, int start) {
25+
if (target == 0) {
26+
List<Integer> newList = new ArrayList<Integer>(list);
27+
28+
resultList.add(newList);
29+
} else if (target > 0) {
30+
for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
31+
if (i > start && candidates[i] == candidates[i - 1]) {
32+
continue;
33+
}
34+
list.add(candidates[i]);
35+
recursive(candidates, target - candidates[i], resultList, list, i + 1);
36+
list.remove(list.size() - 1);
37+
}
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)