题目描述
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
思路
很常规的dfs题,但是由于很久没打dfs代码了,记录一下。
代码
List<List<Integer>> res = new ArrayList<List<Integer>>();
int n, tar;
int[] nums;
// 当前选取的组合,选到了第几个数字,当前和
void dfs(List<Integer> lis, int cur, int s) {
if(cur == n) {
if(s == tar)
res.add(lis);
} else {
// for(int x: lis) System.out.print(x+"\t"); System.out.println("\t,"+cur+"-"+s);
//对于当前数字可选,可不选
// 选,看是否超过,剪枝
if(s + nums[cur] <= tar) {
List<Integer> tmp = new ArrayList<Integer>(lis);
tmp.add(nums[cur]);
dfs(tmp, cur, s + nums[cur]);
}
// 不选
if(true) {
List<Integer> tmp = new ArrayList<Integer>(lis);
dfs(tmp, cur+1, s);
}
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
nums = candidates;
n = candidates.length;
tar = target;
dfs(new ArrayList<Integer>(), 0, 0);
return res;
}
该博客讨论了一种使用深度优先搜索(DFS)解决寻找数组中数字组合以达到特定目标和的问题。示例展示了如何应用DFS算法,包括递归函数的设计和剪枝策略,来找到所有可能的组合。内容涵盖了如何处理重复数字和优化搜索过程,以减少结果的组合数量。
439

被折叠的 条评论
为什么被折叠?



