java-Arraylist没有在递归中正确更新

下面是我的函数,它给出给定数组中的元素求和到特定目标的所有可能性.我可以打印列表,但是结果列表没有更新.

public List<List<Integer>> helper(List<List<Integer>> res,int[] c,int l,int h,int target,List<Integer> temp){
        if(target == 0){
            res.add(temp);
            System.out.println(temp);
            return res;
        }
        if(target < c[l]){
            return res; 
        }
        for(int i = l; i <=h; i++){
            temp.add(c[i]);
            res = helper(res,c,i,h,target-c[i],temp);
            temp.remove(temp.size()-1);
        }
        return res;
    }

res末尾是空数组列表的arraylist,但是第5行正确打印了临时arraylist.

函数如下所示.

List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
res = helper(res,candidates,candidates.length-1,target,temp);

例:
给定数组= [1,2,3],目标= 6

标准输出

[1,1,1]
[1,2]
[1,3]
[1,3]
[2,2]
[3,3]

res is [[],[],[]]
最佳答案
这是针对按值传递问题的标准按引用传递.

您正在将一个temp的引用添加到res对象,因此,只要temp的值更改(在程序中的for循环内执行),它也会更改res中的实例的值,因此最后从所有元素中删除该元素时临时列表变为空,然后将res中的所有值更改为空列表.

如果满足以下条件,则应首先更改您的辅助方法,并且该方法应该起作用:

if(target == 0){
  ArrayList<Integer> copy = new ArrayList<>(temp);
  res.add(copy);
  return res;
}

说明

我们没有创建临时引用到res,而是创建了简单的temp副本,然后将其添加到res.

这样可以防止新的对象值覆盖值.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...