-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombination Sum
More file actions
36 lines (29 loc) · 1015 Bytes
/
Copy pathCombination Sum
File metadata and controls
36 lines (29 loc) · 1015 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
31
32
33
34
35
36
LEETCODE PROBLEM SOLVING
PROBLEM-> COMBINATION SUM
import java.util.*;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), candidates, target, 0);
return result;
}
private void backtrack(List<List<Integer>> result,
List<Integer> temp,
int[] candidates,
int target,
int start) {
// base case
if (target == 0) {
result.add(new ArrayList<>(temp));
return;
}
if (target < 0) return;
for (int i = start; i < candidates.length; i++) {
// choose
temp.add(candidates[i]);
// explore (same i → reuse allowed)
backtrack(result, temp, candidates, target - candidates[i], i);
temp.remove(temp.size() - 1);
}
}
}