Arraylist 没有在递归中正确更新

Gur*_*gde 5 java recursion

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

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;
    }
Run Code Online (Sandbox Code Playgroud)

res 最后是空数组列表的数组列表,但第 5 行正确打印临时数组列表。

该函数的调用如下。

List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
res = helper(res,candidates, 0, candidates.length-1, target, temp);
Run Code Online (Sandbox Code Playgroud)

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

标准输出:

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

res is [[],[],[],[],[],[],[]]
Run Code Online (Sandbox Code Playgroud)

Jai*_*nik 4

这是针对按值传递问题的标准按引用传递

temp您正在向对象添加 a 的引用res,因此每当更改值temp(在程序中执行for loop)时,它也会更改实例的值res,因此最后当从 中删除所有元素时temp,列表变为空并且然后它将所有值更改res为空列表。

如果条件如下,首先更改您的帮助方法,它应该可以工作:

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

解释

我们不是添加 a 的引用tempres而是创建 a 的简单副本temp,然后将其添加到res

这可以防止值被新的对象值覆盖。