题目:
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]
.
要求处理不重复的全排列,可以首先进行排序,生成最小的一组排列,然后不停的执行next Pemutation方法,直到出现重复的为止。
那么如何判断出现了重复的呢,我们可以根据数组是否有效来判断,如果数组有序,则已经又生成到最小元素了,这时就停止遍历
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class No46_PermutationII {
public static void main(String[] args){
System.out.println(permuteUnique(new int[]{1,1,2}));
}
public static List<List<Integer>> permuteUnique(int[] num) {
Arrays.sort(num);
List ret = new ArrayList<List<Integer>>();
List<Integer> e = new ArrayList<Integer>();
for(int j=0;j<num.length;j++){
e.add(num[j]);
}
ret.add(e);
nextPermutation(num);
while(!isIncline(num)){
List<Integer> element = new ArrayList<Integer>();
for(int j=0;j<num.length;j++){
element.add(num[j]);
}
ret.add(element);
nextPermutation(num);
}
return ret;
}
public static boolean isIncline(int[] num){
for(int i=0;i<num.length-1;i++){
if(num[i] > num[i+1])
return false;
}
return true;
}
public static void nextPermutation(int[] num) {
int index = 0;
for(int i=1;i<num.length;i++){
if(num[i]>num[i-1]){
index = i;
}
}
if(index != 0){
int i = index;
while(i< num.length && num[i] > num[index-1]) i++;
num[index-1] += num[i-1];
num[i-1] = num[index-1] - num[i-1];
num[index-1] = num[index-1] - num[i-1];
}
reverse(num, index, num.length-1);
}
public static void reverse(int[] num, int start, int end){
for(int i=0;i<=(end-start)/2;i++){
int tmp = num[start+i];
num[start+i] = num[end-i];
num[end-i] = tmp;
}
}
}