【题目】
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], [2,1,1] ]【解析】
这个题和上一题几乎一样,这里使用非递归法解答,递归法参照第46题即可解答。
【代码】
public List<List<Integer>> permuteUnique(int[] nums) {
LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
int n = nums.length;
Arrays.sort(nums);
List<Integer> temp = new ArrayList<Integer>();
for(int b:nums)
temp.add(b);
res.add(temp);
while(true)
{
int count=-1;
for(int i=n-1;i>0;i--)
if(nums[i-1]<nums[i])
{
count=i-1;
break;
}
if(count==-1)
return res;
for(int i=n-1;i>count;i--)
if(nums[i]>nums[count])
{
swap(nums,count,i);
break;
}
perm(nums,count+1,n-1);
List<Integer> tempList = new ArrayList<Integer>();
for(int b:nums)
tempList.add(b);
res.add(tempList);
}
}
public static void swap(int[] nums,int p,int q){
int temp=nums[p];
nums[p]=nums[q];
nums[q]=temp;
}
public static void perm(int[] nums,int p,int q){
for(int left=p,right=q;left<right;left++,right--)
{
int temp=nums[left];
nums[left]=nums[right];
nums[right]=temp;
}
}