在刷LeetCode時,碰到一個List.add方法的問題
題目如下:https://leetcode-cn.com/problems/combinations/
正確結果應該是:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
1.問題代碼如下
public class No77_combinations { public static void main(String[] args) { List<List<Integer>> lists; lists = new Solution77().combine(4, 2); System.out.println(lists);//問題:最終返回結果為[[], [], [], [], [], []] } } class Solution77 { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> lists = new ArrayList<>(); List<Integer> list = new ArrayList<>(); dfs(n, k, 0, list,lists); return lists; } private List<List<Integer>> dfs(int n, int k, int index, List<Integer> list,List<List<Integer>> lists) { if (k == 0) { lists.add(list);//(*) 發現是這行代碼出了問題 System.out.println(lists);//這里打個斷點調試 return lists; } for (int i = index; i < n; i++) { list.add(i + 1);//嘗試添加 dfs(n, k - 1, i + 1, list,lists); list.remove(list.size() - 1);//回溯,成功與否均進行回溯 } return lists; } }
調試結果為(錯誤):
[[1, 3], [1, 3]] [[1, 4], [1, 4], [1, 4]] [[2, 3], [2, 3], [2, 3], [2, 3]] [[2, 4], [2, 4], [2, 4], [2, 4], [2, 4]] [[3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4]]
查了一些資料才思考出原因:list.add方法傳入的是地址而不是值。
因此:每一次lists.add(list),是將list的引用傳入了,每次回溯進行修改的時候,lists中已經添加的引用值也會改變,才會出現每次打印lists時,都會不同
2. 正確寫法:將(*)代碼重寫,根據list中的值重新new一個對象即可
lists.add(new ArrayList<>(list)); //(*)
斷點處調試結果為:
[[1, 2]] [[1, 2], [1, 3]] [[1, 2], [1, 3], [1, 4]] [[1, 2], [1, 3], [1, 4], [2, 3]] [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4]] [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
最終返回正確結果為
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]