题解 | #有重复项数字的全排列 TreeSet#
有重复项数字的全排列
http://www.nowcoder.com/practice/a43a2b986ef34843ac4fdd9159b69863
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
if (num == null || num.length == 0){
return new ArrayList<>();
}
TreeSet<ArrayList<Integer>> set = new TreeSet<>(new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
for (int i = 0; i < o1.size(); i++) {
if (o1.get(i) != o2.get(i)) return o1.get(i) - o2.get(i);
}
return 0;
}
});
process(num, 0, set);
return new ArrayList<>(set);
}
public static void process(int[] num, int index, TreeSet<ArrayList<Integer>> set){
if (index == num.length){
ArrayList<Integer> list = new ArrayList<>();
for (int i : num) {
list.add(i);
}
set.add(list);
return;
}
for (int i = index; i < num.length; i++) {
swap(num, index, i);
process(num, index + 1, set);
swap(num, index, i);
}
}
public static void swap(int[] num, int i, int j){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}