39. Combination Sum
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]Last updated
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]Last updated
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(candidates); // 这一步可省略
dfs(list, new ArrayList<Integer>(), candidates, target, 0);
return list;
}
public void dfs(List<List<Integer>> list, List<Integer> temp, int[] nums, int remain, int start) {
if (remain < 0) return;
if (remain == 0) list.add(new ArrayList<Integer>(temp)); // 满足条件直接返回
else {
for (int i = start; i < nums.length; i++){
temp.add(nums[i]);
dfs(list, temp, nums, remain - nums[i], i); //i here because one number can be used many times
temp.remove(temp.size() - 1);
}
}
}
}