39. Combination Sum (not use befroe, so int I = start, dfs(i) -> is i !!







Last updated







Last updated
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
helper(res, new ArrayList<>(), candidates, target, 0);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start) {
if (target < 0) {
return;
} else if (target == 0) {
res.add(new ArrayList<>(list));
} else {
for (int i = start; i < candidates.length; i++) {
list.add(candidates[i]);
helper(res, list, candidates, target - candidates[i], i); // pass i, why i = start => for seq search
list.remove(list.size()-1);
}
}
}
}
/*
7 - any of [],
7 = [2,3,6,7]
7 - 2 = 5
5 - 2 = 3
3 - 2 => no, 3 - 3 ok! backtrack
*/class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
dfs(result, candidates, target, new ArrayList<>(), 0);
return result;
}
private void dfs(List<List<Integer>> result, int[] candidates, int target, List<Integer> list, int start) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(list));
return;
}
// if every time from i = 0, will generate like [2,2,3] [2,3,2], [3,2,2]
// just use order seq to pass the i index
for (int i = start; i < candidates.length; i++) {
list.add(candidates[i]);
dfs(result, candidates, target - candidates[i], list, i);
list.remove(list.size()-1);
}
}
}結果 [2,2,3] [2,3,2], [3,2,2] => 如果用 i = 0, 會