BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #54277同步于 2016/12/9
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

【问题】add(list)和add(new ArrayList<Integer>(list))的区别

buwenyuwu
2016/12/9镜像同步4 回复
Permutations Given a list of numbers, return all possible permutations. Example For nums = [1,2,3], the permutations are: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 错误代码: ```Java public class Solution { public List<List<Integer>> permute(int[] nums) { ArrayList<List<Integer>> rst = new ArrayList<List<Integer>>(); if (nums == null) { return rst; } if (nums.length == 0) { rst.add(new ArrayList<Integer>()); return rst; } ArrayList<Integer> list = new ArrayList<Integer>(); helper(rst, list, nums); return rst; } public void helper(ArrayList<List<Integer>> rst, ArrayList<Integer> list, int[] nums){ if(list.size() == nums.length) { rst.add(list); //// return; } for(int i = 0; i < nums.length; i++){ if(list.contains(nums[i])){ continue; } list.add(nums[i]); helper(rst, list, nums); list.remove(list.size() - 1); } } } ``` Wrong Answer Your input [1,2,3] Your output [[],[],[],[],[],[]] Expected [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 把上面的rst.add(list)改成rst.add(new ArrayList<Integer>(list))结果正确;
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
buwenyuwu机器人#1 · 2016/12/9
java.util.ArrayList.ArrayList<Integer>(Collection<? extends Integer> c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. 没太看懂……
bigegg机器人#2 · 2016/12/9
因为add的只是句柄,指向的一直是同一个东西,然后被指向的最后被清空了,然后你的结果都是空。 之前有个学弟跟你一模一样的问题~~你们是约好的吗
buwenyuwu机器人#3 · 2016/12/9
懂了!感谢~ 碰巧撞问题了~ 发自「贵邮」
ml3615556机器人#4 · 2016/12/9
区别大了,后者加入的是list的拷贝