import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>() ;
if(num == null || num.length == 0) return res ;
Arrays.sort(num) ;
help(num , new boolean[num.length] , new ArrayList<>() , res) ;
return res ;
}
public void help(int[] num , boolean[] isVisited, ArrayList<Integer> tmp , ArrayList<ArrayList<Integer>> res) {
if(tmp.size() == num.length) {
res.add(new ArrayList<>(tmp)) ;
return ;
}
for(int i = 0 ; i < num.length ; i ++) {
if(isVisited[i]) continue ;//num[i]已经访问过
//1.当num[i] == num[i-1],如果isVisited[i-1]==true,则说明num[i]和num[i-1]虽然相等,
//但是他们不在同一层(即没有出现在同一个位置,这种请况是允许的,需要考虑)
//2.当num[i] == num[i-1],如果isVisited[i-1]==false,则说明num[i]和num[i-1]既相等,
//又在同一层(即出现在相同的位置,这种情况是重复的,不允许)
if(i > 0 && num[i] == num[i - 1] && !isVisited[i - 1]) continue ;
isVisited[i] = true ;
tmp.add(num[i]) ;
help(num , isVisited , tmp , res) ;
tmp.remove(tmp.size()-1) ;
isVisited[i] = false ;
}
}
}