思路:
递归回溯
public class Solution {
int [] candidates;
int n;
LinkedList<List<Integer>> result;
LinkedList<Integer>temp;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates=candidates;
n=candidates.length;
result=new LinkedList<List<Integer>>();
temp=new LinkedList<Integer>();
help(0,target);
return result;
}
void help(int start,int left)
{
for(int i=start;i<n;i++)
{
int currentLeft=left-candidates[i];
if(currentLeft<0)
{
continue;
}
temp.add(candidates[i]);
if(currentLeft>0)
{
help(i,currentLeft);
}
else// if(currentLeft==0)
{
result.add(new LinkedList<Integer>(temp));
}
temp.removeLast();
}
return;
}
}
本文详细解析了如何使用递归回溯算法解决组合总和问题。通过实例代码展示了如何找到所有可能的组合来达到目标值,并确保每个组合的元素唯一且非降序排列。文章深入探讨了递归调用的过程及其实现细节。
1009

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



