分析摘自:
https://leetcode.com/discuss/18482/share-my-recursive-solution
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]
have
the following unique permutations:
[1,1,2]
, [1,2,1]
,
and [2,1,1]
.
回溯法生成全排列+hash判重,可过,不优。
相同的元素为【源】调用生成重复集合,没有顺序?就规定顺序。
排序后将相同的元素和前面的元素【捆绑】以免重复调用。
The idea to resolve duplicate is to ensure that for elements with the same value, we make sure that they are picked up in the ascending
order of index. To implement this, every time we try to pick up some value, we just check if the previous element has the same value and is visited or not. If so, we just return!
List<List<Integer>> list=new ArrayList<>();
ArrayList<Integer> arraylist=new ArrayList<>();
boolean[] onstack;
public List<List<Integer>> permuteUnique(int[] nums)
{
Arrays.sort(nums);
onstack=new boolean[nums.length];
dfs(nums.length, 0, nums);
return list;
}
public void dfs(int n,int k,int[] nums)
{
if(k==n)
{
list.add(new ArrayList<>(arraylist));
return ;
}
for(int i=0;i<nums.length;i++)
{
if(!onstack[i])
{
if(i>0 &&nums[i-1]==nums[i] && !onstack[i-1])
continue;
arraylist.add(nums[i]);
onstack[i]=true;
dfs(nums.length, k+1 , nums);
onstack[i]=false;
arraylist.remove(arraylist.size()-1);
}
}
}