题目
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]
.
思路
这道题跟Permutations的具体差别就是怎么去掉重复的.
思路如下
我们先排序,然后在递归之前进行消除重复数字的操作。但是这样做还是得不到正确的答案。因为当你交换数字的时候,可能会使后面的数字又无序了.解决方法就是用一个临时数组保存当前的结果,然后对求解数组再次排序,递归回来后在重新赋值就可以了额...
这道题还是卡住了我...LZ果断需要刷刷题啊
代码
public class Solution {
public void swap(int[] a,int p1,int p2)
{
int temp = a[p1];
a[p1] = a[p2];
a[p2] = temp;
}
public void Permutations(int[] num ,int begin, int end, ArrayList<ArrayList<Integer>> result )
{
if(begin>end)
{
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i = 0 ;i <= end; i ++)
{
temp.add(num[i]);
}
result.add(temp);
}
else
{
for(int i = begin; i <=end ; i++)
{
int[] temp = Arrays.copyOf(num, num.length);
Arrays.sort(num, begin, end+1);
if(begin!=i&&num[i]==num[i-1])
{
continue;
}
swap(num,begin,i);
Permutations(num,begin+1,end,result);
num = Arrays.copyOf(temp, temp.length);
swap(num,begin,i);
}
}
}
public boolean isCome (int[] num,int begin,int end)
{
for(int i = begin;i<end;i++)
{
if(num[begin]==num[end])
return true;
}
return false;
}
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num)
{
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if( num.length == 0 )
return result;
Arrays.sort(num);
Permutations(num,0,num.length-1,result);
return result;
}
}