47.Permutations II
https://leetcode.com/problems/permutations-ii/
Last updated
https://leetcode.com/problems/permutations-ii/
Last updated
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result=new ArrayList<>();
if(nums==null){
return result;
}
if(nums.length==0){
result.add(new ArrayList<Integer>());
return result;
}
List<Integer> path=new ArrayList<Integer>();
boolean[] visited=new boolean[nums.length];
Arrays.sort(nums);
dfs(nums,path,result,visited);
return result;
}
public void dfs(int[] nums,List<Integer> path,List<List<Integer>> result,boolean[] visited){
if(path.size()==nums.length){
result.add(new ArrayList<Integer>(path));
return;
}
for(int i=0;i<nums.length;i++){
/*
上面的判断主要是为了去除重复元素影响。
比如,给出一个排好序的数组,[1,2,2],那么第一个2和第二2如果在结果中互换位置,
我们也认为是同一种方案,所以我们强制要求相同的数字,原来排在前面的,在结果
当中也应该排在前面,这样就保证了唯一性。所以当前面的2还没有使用的时候,就
不应该让后面的2使用。
*/
if(visited[i] || (i>0 && nums[i]==nums[i-1] && visited[i-1]==false)){
continue;
}
visited[i]=true;
path.add(nums[i]);
dfs(nums,path,result,visited);
path.remove(path.size()-1);
visited[i]=false;
}
}