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.
這可以防止值被新的對象值覆蓋。

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;
}
添加回答
舉報