Skip to content

Commit 864c3dd

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 40_Combination_Sum_II.java
1 parent 01bb200 commit 864c3dd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
3+
if (candidates == null || candidates.length == 0) {
4+
return Collections.emptyList();
5+
}
6+
7+
Arrays.sort(candidates);
8+
9+
List<List<Integer>> result = new ArrayList<>();
10+
dfs(candidates, target, 0, new ArrayList<>(), result);
11+
return result;
12+
}
13+
14+
private void dfs(int[] candidates, int target, int idx, List<Integer> tempResult, List<List<Integer>> result) {
15+
if (target < 0) {
16+
return;
17+
}
18+
if (target == 0) {
19+
result.add(new ArrayList<>(tempResult));
20+
return;
21+
}
22+
23+
for (int i = idx; i < candidates.length; i++) {
24+
if (i > idx && candidates[i] == candidates[i - 1]) {
25+
continue;
26+
}
27+
tempResult.add(candidates[i]);
28+
dfs(candidates, target - candidates[i], i + 1, tempResult, result);
29+
tempResult.remove(tempResult.size() - 1);
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)