Java 列表的递归混淆
问题出在这里Java 列表的递归混淆,java,recursion,backtracking,Java,Recursion,Backtracking,问题出在这里 numberSet = [2,3,5], target number = 8 output -> [[2,2,2,2],[2,3,3],[3,5]] 我认为这可以通过回溯来解决: public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> result = new LinkedList<
numberSet = [2,3,5], target number = 8
output -> [[2,2,2,2],[2,3,3],[3,5]]
我认为这可以通过回溯来解决:
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
permutation(candidates, target, new LinkedList(), result);
return result;
}
public void permutation(int[] candidates, int target, List<Integer> subresult, List<List<Integer>> result){
if(target == 0){
result.add(subresult);
return;
}
for(int x: candidates){
if(target - x >= 0){
subresult.add(x);
permutation(candidates, target - x, subresult, result);
subresult.remove(subresult.size() - 1);
}
}
return;
}
他们都是空名单。。。
我想弄清楚为什么我会在条件满足时打印出每个步骤
if(target == 0){
result.add(subresult);
System.out.println(result);
return;
}
他很满意。
我认为我的代码确实找到了解决方案(即使我还没有弄清楚如何删除这些重复项)
为什么会发生这种情况???为什么结果列表仍然是空的?
非常感谢 您的方法是正确的,但是因为您正在删除subresult的最后一个值-
subresult.remove(subresult.size()-1)在每个递归方法调用中,由于result只添加对子结果的引用,因此对子结果的每个添加/删除操作也会在结果中更改
总之-
如果子结果是[1,2,3]
然后将其添加到结果中,然后result=[1,2,3]
但现在如果您从子结果中删除3
,那么结果也会变成[1,2]
所以为了避免这个,
result.add(新链接列表(子结果))代码>
这将使用传入列表的值创建一个新的列表对象。非常感谢!!!这个解释真的很有帮助!
if(target == 0){
result.add(subresult);
System.out.println(result);
return;
}
[[2, 2, 3]]
[[2, 3, 2], [2, 3, 2]]
[[3, 2, 2], [3, 2, 2], [3, 2, 2]]
[[7], [7], [7], [7]]