无标题

最是人间留不住,朱颜辞镜花辞树。这篇文章主要讲述无标题相关的知识,希望能为你提供帮助。


题目传送地址: ??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;

【无标题】


    推荐阅读