-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCombinationSum.java
More file actions
26 lines (23 loc) · 849 Bytes
/
CombinationSum.java
File metadata and controls
26 lines (23 loc) · 849 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
package com.dbc;
import java.util.ArrayList;
import java.util.List;
public class CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
dfs(candidates, target, res, new ArrayList<>(), 0);
return res;
}
private void dfs(int[] candidates, int total, List<List<Integer>> res, List<Integer> nums, int start) {
if (start == candidates.length) return;
if (total == 0) {
res.add(new ArrayList<>(nums));
return;
}
dfs(candidates, total, res, nums, start + 1);
if (total - candidates[start] >= 0) {
nums.add(candidates[start]);
dfs(candidates, total - candidates[start], res, nums, start);
nums.remove(nums.size() - 1);
}
}
}