Skip to content

Commit c4c3c33

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

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

algorithms/CombinationSum/README.md

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

0 commit comments

Comments
 (0)