设为首页 加入收藏

TOP

Permutations II
2014-11-23 17:55:54 】 浏览:2413
Tags:Permutations
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;  
    }  
}  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇VC++自定义对话框程序界面图标以.. 下一篇CWnd *和HWnd转换

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目