怎样做一元购网站,网页站点怎么命名,周至做网站,建设电商平台给你一个 无重复元素 的整数数组 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
组合总数系列题最简单的这个还好只要你会递归就行啥回溯不回溯的都不重要又不需要恢复现场这个题重点是剪枝其他的就不多说了上代码看不懂的请留言或者私信收到第一时间解答
class Solution {/**这个题我准备使用最简单的回溯方法定义函数dfs表示我们当前要尝试candidates的curIndex位置还有targetLeft的和需要凑出一旦出现targetLeft为0的就加到结果里 */public ListListInteger combinationSum(int[] candidates, int target) {/**数组长度比较小先排个序*/Arrays.sort(candidates);return dfs(candidates, 0, target);}public ListListInteger dfs(int[] candidates, int curIndex, int targetLeft) {ListListInteger ans new ArrayList();if(targetLeft 0) {/**如果出现了小于0的情况说明前面的过程错误本次尝试无效 */return ans;}if(targetLeft 0) {/**如果为0了说明这是一次成功的常识返回添加空元素的ans */ans.add(new ArrayList());return ans;}/**如果targetLeft不是0但是没有数可以尝试了也是失败的 */if(curIndex candidates.length) {return ans;}/**当前数组按照从小到达排序如果targetLeft小于当前数则当前数及其后面的数不用再尝试,整体失败*/if(targetLeft candidates[curIndex]) {return ans;}/**其他情况正常尝试当前位置的数可以使用0~targetLeft/candicates[curIndex]次*/for(int num 0; num targetLeft/candidates[curIndex]; num ) {ListListInteger ansNext dfs(candidates, curIndex 1, targetLeft - num * candidates[curIndex]);for(ListInteger list : ansNext) {/**当前位置的数使用了多少个就加多少个题目没有要求加在最前面建议直接add否则使用list.add(0,candidates[curIndex])*/for(int i 0; i num; i) {list.add(candidates[curIndex]);}ans.add(list);}}return ans;}
}