Permutations II

2014-11-23 17:55:54 · 作者: · 浏览: 16
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].
Discuss
java code: (code is the documents.)
public class Solution {  
    public ArrayList> permuteUnique(int[] num) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        ArrayList> res = new ArrayList>();  
        if(num.length == 0)  
            return res;  
        ArrayList tmp = new ArrayList();  
        Arrays.sort(num);  
        for(int i = 0 ; i < num.length; i++)  
            tmp.add(num[i]);  
        res.add(new ArrayList(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
(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; } }