Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
这题不知道出了什么意外,输入[0,1]在Eclipse上运行结果:[[0, 1], [1, 0]]
LeetCode上运行结果:[[1],[0,1],[1,0]]
简直了.....晕。是什么原因还有待解决。
public static List<List<Integer>> ans=new ArrayList<List<Integer>>(); public static List<List<Integer>> permute(int[] nums) { int l=nums.length; List<Integer> temp=new ArrayList<Integer>(); if(l==0) return ans; if(l==1){ temp.add(nums[0]); ans.add(temp); return ans; } Arrays.sort(nums); dfs(temp, nums, new boolean[nums.length]); return ans; } public static void dfs(List<Integer> temp,int[] num,boolean [] used){ if(temp.size() == num.length){ ans.add(new ArrayList(temp));//add a copy return; } for(int i = 0; i < num.length; i++){ //if(i > 0 && !used[i-1] && num[i] == num[i-1]) continue;// judge duplicate number if(!used[i]){ temp.add(num[i]); used[i] = true; dfs(temp, num, used); temp.remove(temp.size() - 1); used[i] = false; } } }
时间: 2024-10-27 07:00:55