Skip to content

Commit 7e0dcd3

Browse files
40. Combination Sum II (java)
1 parent 07853ac commit 7e0dcd3

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
3+
private List<List<Integer>> result = new ArrayList<>();
4+
5+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
6+
Arrays.sort(candidates);
7+
combinationSum(candidates,target,candidates.length-1, new ArrayList<>());
8+
return result;
9+
}
10+
11+
private void combinationSum(int[] candidates, int target,int length, List<Integer> integers) {
12+
List<Integer> list;
13+
for (int i = length; i >= 0; i--) {
14+
int nc = candidates[i];
15+
if (nc>target || i<length && nc==candidates[i+1]) continue;
16+
list = new ArrayList<>(integers);
17+
list.add(nc);
18+
if (nc==target) result.add(list);
19+
else combinationSum(candidates, target - nc, i-1, list);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)