欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > LeetCode39:组合总和

LeetCode39:组合总和

2025/11/11 10:13:49 来源:https://blog.csdn.net/sinat_32502451/article/details/142736453  浏览:    关键词:LeetCode39:组合总和

题目:

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

思路:

  • 回溯法
  • 选择当前数。添加到组合列表中。递归。回溯

代码:

class Solution {public List<List<Integer>> combinationSum(int[] candidates, int target ) {List<List<Integer>> resultList = new ArrayList<>();List<Integer> list = new ArrayList<>();dfs(candidates, target, resultList, list, 0);return resultList;}public void dfs(int[] candidates, int target, List<List<Integer>> resultList, List<Integer> list,  int idx) {//如果遍历完了数组,就结束if (idx == candidates.length) {return;}//达到了目标值,就添加到结果列表中if (target == 0) {resultList.add(new ArrayList<>(list));return;}//在决策中,可以选择跳过不用第 idx 个数。也可以选择像后面代码,选择第 idx 个数dfs (candidates, target , resultList, list, idx+1);// 如果已经大于我们所需的target 值,说明已经不满足条件了。终止递归。if (target - candidates[idx] >=0) {//选择第 idx 个数。添加到列表中list.add( candidates[idx]);//递归。目标值去掉已经添加的值dfs (candidates, target-candidates[idx] , resultList, list, idx);//回溯list.remove( list.size()-1);           }}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词