返回信息流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))结果正确;
这是一条镜像帖。来源:北邮人论坛 / java / #54277同步于 2016/12/9
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
【问题】add(list)和add(new ArrayList<Integer>(list))的区别
buwenyuwu
2016/12/9镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
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.
没太看懂……