做标准件网站,哈尔滨建设信息网,网站外链建设教程,wordpress建站做客户端组合总和
题目描述#xff1a; 给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target #xff0c;找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 #xff0c;并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个…组合总和
题目描述 给你一个 无重复元素 的整数数组 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
输出: []提示
1 candidates.length 302 candidates[i] 40candidates 的所有元素 互不相同1 target 40
思路分析 使用深度优先遍历 实现使用一个列表在 深度优先遍历 变化的过程中遍历所有可能的列表并判断当前列表是否符合题目的要求。如果不符合进行剪枝。
说明
以 target 7 为 根结点 创建一个分支的时 做减法 每一个箭头表示从父亲结点的数值减去边上的数值得到孩子结点的数值。边的值就是题目中给出的 candidate 数组的每个元素的值减到 0或者负数的时候停止即结点 0和负数结点成为叶子结点同时每一次搜索的时候设置 下一轮搜索的起点 begin即从每一层的第 222 个结点开始都不能再搜索产生同一层结点已经使用过的 candidate 里的元素。
代码实现注解
class Solution {public ListListInteger combinationSum(int[] candidates, int target) {//定义一个返回结果的集合ListListInteger res new ArrayList();//定义一个存储树路径上的节点值int len candidates.length;if(len 0)return res;//升序排序Arrays.sort(candidates);//定义一个表示数组的长度变量DequeInteger path new ArrayDeque();//深度搜索调用函数dfs(candidates, 0, len, target, path, res);return res;}private void dfs(int[] candidates, int begin, int len, int target, DequeInteger path,ListListInteger res) {// 由于进入更深层的时候小于 0 的部分被剪枝因此递归终止条件值只判断等于 0 的情况if (target 0) {//将节点值存入返回集合res.add(new ArrayList(path));return;}//begin用于记录当前遍历位置for (int i begin; i len; i) {//剪枝操作将叶子节点小于0的分支减掉if (target - candidates[i] 0) {break;}path.addLast(candidates[i]);//将i传入可有效避免结果重复dfs(candidates, i, len, target - candidates[i], path, res);//回溯移除path中最后一个元素path.removeLast();}}
}