加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:26:14 所属栏目:Java 来源:网络整理
导读:下面是我的函数,它给出给定数组中的元素求和到特定目标的所有可能性.我可以打印列表,但是结果列表没有更新. public ListListInteger helper(ListListInteger res,int[] c,int l,int h,int target,ListInteger temp){ if(target == 0){ res.add(temp); System

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

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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读