public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new LinkedList<>();
if (candidates == null || candidates.length == 0) {
return res;
}
List<Integer> list = new LinkedList<>();
Arrays.sort(candidates);
helper(res, list, candidates, target, 0, 0);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int sum, int pos) {
if (sum == target) {
res.add(new LinkedList<>(list));
return;
}
for (int i = pos; i < candidates.length; i++) {
if (sum + candidates[i] > target) {
return;
}
list.add(candidates[i]);
helper(res, list, candidates, target, sum + candidates[i], i);
list.remove(list.size() - 1);
}
}
}Combination Sum
最新推荐文章于 2025-05-25 18:32:47 发布
本文详细解析了如何使用递归实现组合总和算法,通过一个Java示例代码展示了寻找所有可能的组合使得候选数之和等于目标数的过程。文章重点介绍了核心函数helper的设计思路及其参数意义。
144

被折叠的 条评论
为什么被折叠?



