微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

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

原文地址:https://www.jb51.cc/java/532860.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐