无标题
Posted Java全栈研发大联盟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无标题相关的知识,希望对你有一定的参考价值。
题目传送地址: https://leetcode.cn/problems/combination-sum/submissions/
代码如下
//递归解法
public static List<List<Integer>> combinationSum(int[] candidates, int target)
//排序
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < candidates.length; i++)
List<List<Integer>> combination = combination(candidates, i, target);
if (!combination.isEmpty())
result.addAll(combination);
return result;
//算出以位置i的元素结尾,且符合最终结果的list
public static List<List<Integer>> combination(int[] candidates, int i, int target)
List<List<Integer>> result = new ArrayList<>();
if (i == 0)
if (target % candidates[0] == 0)
List<Integer> list = new ArrayList<>();
while (target > 0)
list.add(candidates[0]);
target = target - candidates[0];
result.add(list);
return result;
else
return result;
if (candidates[i] == target)
result.add(Arrays.asList(target));
return result;
int[] range = Arrays.copyOfRange(candidates, 0, i);
int count = 0;
while (target >= candidates[i])
int lastIndex = i - 1;
count++;
while (lastIndex >= 0)
List<List<Integer>> lists = combination(range, lastIndex, target - candidates[i]);
if (!lists.isEmpty())
for (List<Integer> list : lists)
List<Integer> integers = new ArrayList<>(list);
for (int m = 0; m < count; m++)
integers.add(candidates[i]);
result.add(integers);
lastIndex--;
target = target - candidates[i];
return result;
以上是关于无标题的主要内容,如果未能解决你的问题,请参考以下文章
剑指 Offer 27. 二叉树的镜像无取巧解法,易于理解!