题解 | #有重复项数字的全排列#
有重复项数字的全排列
https://www.nowcoder.com/practice/a43a2b986ef34843ac4fdd9159b69863
import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> permuteUnique(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; } List<Integer> tempList=new ArrayList<>(); for (int i = k; i < nums.length; i++) { if(i!=k&&nums[i]==nums[k]||tempList.contains(nums[i])){ continue; } swap(nums, k, i); dfs(nums, ret, k + 1); swap(nums, k, i); tempList.add(nums[i]); } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }