Skip to content

Commit 8452854

Browse files
committed
conbinationsum
1 parent df960d3 commit 8452854

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/combination-sum/
8+
public class CombinationSum {
9+
10+
public static void main(String[] args) {
11+
CombinationSum obj = new CombinationSum();
12+
int[] candicates = {2, 3, 6, 7};
13+
int target = 7;
14+
List<List<Integer>> resultList = obj.combinationSum(candicates, target);
15+
System.out.println(Arrays.toString(resultList.toArray()));
16+
}
17+
18+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
19+
List<List<Integer>> resultList = new ArrayList<>();
20+
Arrays.sort(candidates);
21+
recursive(candidates, target, 0, new ArrayList<>(), resultList);
22+
23+
return resultList;
24+
}
25+
26+
public void recursive(int[] candidates, int target, int start, List<Integer> list, List<List<Integer>> resultList) {
27+
if (target > 0) {
28+
for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
29+
list.add(candidates[i]);
30+
recursive(candidates, target - candidates[i], i, list, resultList);
31+
list.remove(list.size() - 1);
32+
}
33+
} else if (target == 0) {
34+
resultList.add(new ArrayList<>(list));
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)