题解 | #没有重复项数字的全排列#
没有重复项数字的全排列
https://www.nowcoder.com/practice/4bcf3081067a4d028f95acee3ddcd2b1
import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> permute(int[] num) { ArrayList<ArrayList<Integer>> ret=new ArrayList<ArrayList<Integer>>(); int len=num.length; dfs(num,ret,0); Collections.sort(ret, new Comparator<ArrayList<Integer>>() { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { StringBuilder oo1 = new StringBuilder(); StringBuilder oo2 = new StringBuilder(); o1.stream().forEach(x -> oo1.append(x)); o2.stream().forEach(x -> oo2.append(x)); return o1.toString().compareTo(o2.toString()); } }); return ret; } public void dfs(int[] nums,ArrayList<ArrayList<Integer>> ret,int k){ if(k==nums.length){ ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<nums.length;i++){ list.add(nums[i]); } ret.add(list); return; } for(int i=k;i<nums.length;i++){ swap(nums,k,i); dfs(nums,ret,k+1); swap(nums,k,i); } } public void swap(int[]nums,int i,int j){ int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } }