什么网站能看到专业的做面包视频,网站管理公司,网站开发的需求分析教学视频,长沙建站优化39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target #xff0c;找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 #xff0c;并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重…39. 组合总和
给你一个 无重复元素 的整数数组 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]]
方法搜索回溯
class Solution {public ListListInteger combinationSum(int[] candidates, int target) {ListListInteger ans new ArrayListListInteger();ListInteger combine new ArrayListInteger();dfs(candidates, target, ans, combine, 0);return ans;}public void dfs(int[] candidates, int target, ListListInteger ans, ListInteger combine, int idx) {if (idx candidates.length) {return;}if (target 0) {ans.add(new ArrayListInteger(combine));return;}// 直接跳过dfs(candidates, target, ans, combine, idx 1);// 选择当前数if (target - candidates[idx] 0) {combine.add(candidates[idx]);dfs(candidates, target - candidates[idx], ans, combine, idx);combine.remove(combine.size() - 1);}}
}这段代码是一个Java程序实现了一个名为Solution的类该类包含两个方法combinationSum和dfs。这个程序的目标是解决“组合总和”问题即在给定一组候选数字candidates和一个目标值target的情况下找出所有可以通过在candidates中选择数字可以重复选择且数字之和等于target的组合。返回的组合放在一个列表中每个组合也是一个数字列表。
方法解析 combinationSum方法 输入int[] candidates候选数字数组int target目标和。输出ListListInteger所有和为目标值的组合列表。逻辑首先初始化结果列表ans和一个临时组合列表combine。然后调用深度优先搜索DFS方法dfs来递归寻找所有可能的组合。最后返回结果列表ans。 dfs方法 输入int[] candidatesint targetListListInteger ans累计结果ListInteger combine当前组合int idx当前搜索的起始下标。逻辑 基本情况如果搜索到了数组末尾idx candidates.length直接返回表示这一分支搜索完毕。目标达成如果当前目标和为0说明找到了一个有效的组合将当前组合添加到结果列表ans中然后返回。递归搜索 不选择当前数直接跳过当前数递归调用dfs方法进入下一个数字的搜索即dfs(candidates, target, ans, combine, idx 1)。选择当前数如果当前数可以用于减小目标和即target - candidates[idx] 0则将当前数添加到组合中并递归调用dfs方法以减去当前数的值继续搜索。搜索完成后通过combine.remove(combine.size() - 1)移除最后添加的数进行回溯以尝试其他组合。
通过这种方式程序能够有效地遍历所有可能的组合找出所有满足条件的解并返回这些组合。