那些网站用不着做优化,博客网站排名大全,广告做图网站,西宁是哪个省的城市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]] 示例 3 输入: candidates [2], target 1
输出: []提示 1 candidates.length 302 candidates[i] 40candidates 的所有元素 互不相同1 target 40 状态完成
思路这题用回溯解决问题要求的是在candidates里任意选取数字的和为target的组合有几种情况所以我们用list来装载结果用path来记录当前的组合情况在回溯的函数中用sum表示当前回溯的和的大小index表示从哪里开始避免重复选取。确定回溯的返回条件一是当sum大于目标值的时候返回二是当sum等于目标值的时候返回并且把结果添加到集合中。
class Solution {ListListInteger list new ArrayList();LinkedListInteger pathnew LinkedList();public ListListInteger combinationSum(int[] candidates, int target) {Arrays.sort(candidates);backtraking(0,candidates,target,0);return list;}public void backtraking(int sum,int[] candidates,int target,int index){if(sumtarget){ArrayList newListnew ArrayList(path);list.add(newList);return;}if(sumtarget) return;for(int iindex;icandidates.length;i){if(sumcandidates[i]target) break;path.add(candidates[i]);System.out.println(path sum i);backtraking(sumcandidates[i],candidates,target,i);path.removeLast();}}
} 40. 组合总和 II 给定一个候选人编号的集合 candidates 和一个目标数 target 找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用 一次 。 注意解集不能包含重复的组合。 示例 1: 输入: candidates [10,1,2,7,6,1,5], target 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
] 示例 2: 输入: candidates [2,5,2,1,2], target 5,
输出:
[
[1,2,2],
[5]
] 提示: 1 candidates.length 1001 candidates[i] 501 target 30 状态一开始超时了周赛还没来得及看解析