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]
.
java code: (code is the documents.)
public class Solution {
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num.length == 0)
return res;
ArrayList<Integer> tmp = new ArrayList<Integer>();
Arrays.sort(num);
for(int i = 0 ; i < num.length; i++)
tmp.add(num[i]);
res.add(new ArrayList<Integer>(tmp));
if(num.length <= 1)
return res;
while(true)
{
if(!nextPermutation(num))
break;
tmp.clear();
for(int i = 0 ; i < num.length; i++)
tmp.add(num[i]);
if(!res.contains(tmp))
res.add(new ArrayList<Integer>(tmp));
}
return res;
}
//check whether the array has next permutation.
public boolean nextPermutation(int[] num)
{
if(num.length <= 1)
return false;
for(int i = num.length - 2; i >= 0; i--)
{
if(num[i] < num[i+1])
{
int j;
for(j = num.length - 1; j >= i; j--)
if(num[i] < num[j])
break;
// swap the two numbers.
num[i] = num[i] ^ num[j];
num[j] = num[i] ^ num[j];
num[i] = num[i] ^ num[j];
//sort the rest of arrays after the swap point.
Arrays.sort(num, i+1, num.length);
return true;
}
}
return false;
}
}