码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations II

时间:2014-10-14 12:20:08      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   java   for   sp   

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].

答案

public class Solution {
    public List<Integer> toList(int[] num)
    {
        List<Integer> p = new ArrayList<Integer>(num.length);
        for (int element : num)
        {
            p.add(element);
        }
        return p;
    }

    public void swap(int[] num, int i, int j)
    {
        int p = num[i];
        num[i] = num[j];
        num[j] = p;
    }

    public List<List<Integer>> permuteUnique(int[] num)
    {
        List<List<Integer>> result = new LinkedList<List<Integer>>();
        if (num == null || num.length <= 0)
        {
            return result;
        }
        Arrays.sort(num);

        result.add(toList(num));
        int i;
        int j;
        while (true)
        {
            for (i = num.length - 1; i > 0; i-- )
            {
                if (num[i] > num[i - 1])
                {
                    break;
                }
            }
            if (i == 0)
            {
                break;
            }
            for (j = num.length - 1; j > 0; j-- )
            {
                if (num[j] > num[i - 1])
                {
                    break;
                }
            }
            swap(num, i - 1, j);
            j = num.length - 1;
            while (i < j)
            {
                swap(num, i, j);
                i++ ;
                j-- ;
            }
            result.add(toList(num));
        }
        return result;
    }
}


Permutations II

标签:style   blog   color   io   os   ar   java   for   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/40072479

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!