-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCombinationSum.java
26 lines (22 loc) · 924 Bytes
/
CombinationSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main.java.topcodingquestion.backtracking;
import java.util.ArrayList;
import java.util.List;
//https://leetcode.com/problems/combination-sum/
public class CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<Integer>(), target, candidates, 0);
return result;
}
private void backtrack(List<List<Integer>> result, ArrayList<Integer> tempList, int target, int[] candidates, int start) {
if (target < 0)
return;
if (target == 0)
result.add(new ArrayList<Integer>(tempList));
for (int i = start; i < candidates.length; i++) {
tempList.add(candidates[i]);
backtrack(result, tempList, target - candidates[i], candidates, i);
tempList.remove(tempList.size() - 1);
}
}
}