Skip to content

Commit 3425912

Browse files
committed
add better solution for Combination Sum II in README
1 parent c4c3c33 commit 3425912

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

algorithms/CombinationSumII/README.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,32 @@
11
# Combination Sum II
2-
We can solve this proble by Backtracking Algorithm like [Combination Sum](./CombinationSum)
2+
We can solve this proble by Backtracking Algorithm like [Combination Sum](./CombinationSum), the better solution is like below:
3+
```java
4+
class Solution {
5+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
6+
List<List<Integer>> res = new ArrayList<List<Integer>>();
7+
Arrays.sort(candidates);
8+
backTrack(0, candidates, new ArrayList<Integer>(), target, res);
9+
return res;
10+
}
11+
12+
public void backTrack(int beg, int[] candidates, List<Integer> temp, int target, List<List<Integer>> res) {
13+
if (target == 0) {
14+
res.add(temp);
15+
} else {
16+
int i = beg;
17+
while (i < candidates.length) {
18+
int c = candidates[i];
19+
if (c <= target) {
20+
List<Integer> t = new ArrayList<Integer>(temp);
21+
t.add(c);
22+
backTrack(i + 1, candidates, t, target - c, res);
23+
while (i + 1 < candidates.length && candidates[i + 1] == c) {
24+
i++;
25+
}
26+
}
27+
i++;
28+
}
29+
}
30+
}
31+
}
32+
```

0 commit comments

Comments
 (0)