-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_1_Combination_Sum.java
More file actions
30 lines (26 loc) · 954 Bytes
/
Problem_1_Combination_Sum.java
File metadata and controls
30 lines (26 loc) · 954 Bytes
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
27
28
29
30
package Backtracking;
// Problem Statement: Combination Sum (medium)
// LeetCode Question: 39. Combination Sum
import java.util.ArrayList;
import java.util.List;
public class Problem_1_Combination_Sum {
public List<List<Integer>> combinationSum(int[] candidates, int target){
List<List<Integer>> res = new ArrayList<>();
backtrack(candidates, 0, target, new ArrayList<>(), res);
return res;
}
private void backtrack(int[] candidates, int start, int target, List<Integer> comb, List<List<Integer>> res){
if (target == 0) {
res.add(new ArrayList<>(comb));
return;
}
for (int i = start; i < candidates.length; i++) {
if (target < candidates[i]) {
continue;
}
comb.add(candidates[i]);
backtrack(candidates, i, target - candidates[i], comb, res);
comb.remove(comb.size() - 1);
}
}
}