题目来源:https://leetcode.cn/problems/Ygoe9J/
大致题意:
给定一个不含重复元素的数组,和一个整数 target,在可以重复选择数组某一元素的条件下,返回所有和为 target 的集合
思路
对于一个元素 nums[i] 来说,它在和为 target 的集合中最多出现 target / nums[i] 次
于是对于每个元素,枚举它出现 0 - target / nums[i] 次,每次枚举后递归下一个位置重新枚举,直至当前集合和大于等于 target,或者枚举至数组末尾
代码:
public class CombinationSum {
List<List<Integer>> ans;
int[] nums;
int target;
int n;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
ans = new ArrayList<>();
nums = candidates;
this.target = target;
n = nums.length;
dfs(0, new ArrayList<>(), 0);
return ans;
}
/**
*
* @param idx 当前枚举到的数组索引
* @param list 当前集合
* @param cur 当前集合和
*/
public void dfs(int idx, List<Integer> list, int cur) {
// 若当前集合和等于 target,将当前集合加入答案
if (cur == target) {
ans.add(new ArrayList<>(list));
return;
}
// 当前集合和大于 target 或者枚举至数组末尾时,结束递归
if (cur > target || idx == n) {
return;
}
int rest = target - cur;
int count = rest / nums[idx];
// 枚举当前数 0 - rest / nums[idx] 次,再多集合和就会大于 target
for (int i = 0; i <= count; i++) {
if (i > 0) {
list.add(nums[idx]);
cur += nums[idx];
}
dfs(idx + 1, list, cur);
}
// 回溯
while (count-- > 0) {
list.remove(list.size() - 1);
}
}
}