forked from seanprashad/leetcode-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39_Combination_Sum.java
More file actions
27 lines (24 loc) · 889 Bytes
/
39_Combination_Sum.java
File metadata and controls
27 lines (24 loc) · 889 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
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) {
return Collections.emptyList();
}
List<List<Integer>> result = new ArrayList<>();
dfs(candidates, target, 0, new ArrayList<>(), result);
return result;
}
private void dfs(int[] candidates, int target, int idx, List<Integer> tempResult, List<List<Integer>> result) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(tempResult));
return;
}
for (int i = idx; i < candidates.length; i++) {
tempResult.add(candidates[i]);
dfs(candidates, target - candidates[i], i, tempResult, result);
tempResult.remove(tempResult.size() - 1);
}
}
}