亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Arraylist 沒有以遞歸方式正確更新

Arraylist 沒有以遞歸方式正確更新

侃侃無極 2022-07-06 10:44:24
下面是我的函數,它給出了給定數組中的元素總和到特定目標的所有可能性。我可以打印列表,但是結果列表沒有更新。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 最后是空數組列表的數組列表,但第 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);示例:給定數組 = [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 [[],[],[],[],[],[],[]]
查看完整描述

2 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

這是針對按值傳遞問題的標準引用傳遞。


您正在添加temp對res對象的引用,因此每當temp更改的值(for loop在您的程序中發生)時,它也會更改實例的值,res因此最后當所有元素已從 中刪除時temp,列表變為空并且然后它將所有值更改res為一個空列表。


如果條件如下,則首先更改您的輔助方法,它應該可以工作:


if(target == 0){

  ArrayList<Integer> copy = new ArrayList<>(temp);

  res.add(copy);

  return res;

}

解釋


我們不是添加對 a 的引用temp,res而是創建一個簡單的副本,temp然后將其添加到res.


這可以防止值被新的對象值覆蓋。


查看完整回答
反對 回復 2022-07-06
?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

每次您將 temp 添加到res. 因此,每次您temp向列表添加相同的引用時res。最后temp將是一個空列表,因此其中的所有值都res將是空的,因為它們指向相同的temp引用。如果您為 temp 傳遞新列表,則可以解決此問題。


public static 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], new ArrayList<Integer>(temp));

            temp.remove(temp.size()-1);

        }

        return res;

    }

http://img1.sycdn.imooc.com//62c4f72e0001ba0412890531.jpg

查看完整回答
反對 回復 2022-07-06
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號