Skip to content

Commit 9244ea9

Browse files
Create 40-Combination-Sum-II.java
1 parent 0254eef commit 9244ea9

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

java/40-Combination-Sum-II.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
3+
Arrays.sort(candidates);
4+
List<List<Integer>> ans = new ArrayList<List<Integer>>();
5+
List<Integer> ls = new ArrayList<Integer>();
6+
comb(candidates, target, ans, ls, 0);
7+
return ans;
8+
}
9+
10+
public void comb(int[] candidates, int target, List<List<Integer>> ans, List<Integer> ls, int index) {
11+
if (target == 0) {
12+
ans.add(new ArrayList(ls));
13+
}
14+
else if (target<0)
15+
return;
16+
else {
17+
for (int i = index; i<candidates.length; i++) {
18+
if(i>index && candidates[i] == candidates[i-1]) continue;
19+
ls.add(candidates[i]);
20+
comb(candidates, target-candidates[i], ans, ls, i+1);
21+
ls.remove(ls.get(ls.size()-1));
22+
}
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)