给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
let combinationSum = (candidates, target) => {
let dfs = (nums, target, start, list) => {
if (target === 0) {
ret.push(list.slice());
return;
}
for (let i = start; i < nums.length; i++) {
if (nums[i] <= target) {
list.push(nums[i]);
dfs(nums, target - nums[i], i, list);
list.pop();
}
}
}
let ret = []
if (candidates === null || candidates.length === 0)
return ret;
dfs(candidates, target, 0, []);
return ret;
}
func combinationSum(candidates []int, target int) [][]int {
var res [][]int
if len(candidates) == 0 {
return res
}
var dfs func(nums []int, target int, start int, list []int)
dfs = func(nums []int, target int, start int, list []int) {
if target == 0 {
res = append(res, append([]int{}, list...))
return
}
for i := start; i < len(nums); i++ {
if nums[i] <= target {
list = append(list, nums[i])
dfs(nums, target - nums[i], i, list)
list = list[0:len(list) - 1]
}
}
}
dfs(candidates, target, 0, []int{})
return res
}
class Solution {
List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0)
return ret;
dfs(candidates, target, 0, new ArrayList<Integer>());
return ret;
}
public void dfs(int[] nums, int target, int start, ArrayList<Integer> list){
if (target == 0) {
ret.add(new ArrayList(list));
return;
}
for (int i = start; i < nums.length; i++){
if (nums[i] <= target) {
list.add(nums[i]);
dfs(nums, target - nums[i], i, list);
list.remove(list.size() - 1);
}
}
}
}