欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > 代码随想录——组合总和(Leetcode LCR81)

代码随想录——组合总和(Leetcode LCR81)

2024/10/24 11:12:01 来源:https://blog.csdn.net/qq_46574748/article/details/139700885  浏览:    关键词:代码随想录——组合总和(Leetcode LCR81)

题目链接
在这里插入图片描述

回溯

class Solution {List<List<Integer>> res = new ArrayList<List<Integer>>();List<Integer> list = new ArrayList<Integer>();public List<List<Integer>> combinationSum(int[] candidates, int target) {backtracking(candidates, target, 0, 0);return res;}public void backtracking(int[] candidates, int target, int sum, int startIndex){if(sum > target){return;}if(sum == target){res.add(new ArrayList<>(list));return;}for(int i = startIndex; i < candidates.length; i++){sum += candidates[i];list.add(candidates[i]);// 数字可以无限制重复被选取,所以i不用+1backtracking(candidates, target, sum, i);sum -= candidates[i];list.removeLast();}}
}

版权声明:

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

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