力扣(LeetCode)47

栏目: 编程工具 · 发布时间: 7年前

内容简介:题目地址:题目描述:

题目地址:

https://leetcode-cn.com/probl...

题目描述:

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]

输出:

[

[1,1,2],

[1,2,1],

[2,1,1]

]

解答:

这一题可以利用求下一个排列算法来求解,对原数组排序,然后加入一个结果,接着不断求下一个排列,直到没有下一个排列为止。而下一个排列的求解,可以参考下一个排列

java ac代码:

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>>ans = new ArrayList(1000);
        Arrays.sort(nums);
        List<Integer> temp = new ArrayList();
        for(int i = 0;i < nums.length;i++)
            temp.add(nums[i]);
        ans.add(temp);
        
        while(true)
        {
            temp = nextpermute(nums);
            if(temp.size() > 0)
                ans.add(temp);
            else break;
        }
        return ans;
    }
    
    List<Integer> nextpermute(int[]nums)
    {
        List<Integer>ans = new ArrayList(nums.length);
        for(int i = 0;i < nums.length-1;i++)
            if(nums[i]<nums[i+1])
            {
                int j = nums.length-1;
                while(true)
                {
                    if(nums[j-1] < nums[j])
                        break;
                    j--;
                }
                int k = nums.length-1;
                while(true)
                {
                    if(nums[k] > nums[j-1])
                    {
                        swap(nums,j-1,k);
                        int l = j,r = nums.length-1;
                        while(l < r)
                        {
                            swap(nums,l,r);
                            l++;
                            r--;
                        }
                        for(int q = 0;q < nums.length;q++)
                            ans.add(nums[q]);
                        break;
                    }
                    k--;
                }
                
                
                break;
            }
        return ans;
    }
    
    void swap(int[]nums,int i,int j)
    {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

以上所述就是小编给大家介绍的《力扣(LeetCode)47》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Development with Rails 4

Agile Web Development with Rails 4

Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2013-10-11 / USD 43.95

Ruby on Rails helps you produce high-quality, beautiful-looking web applications quickly. You concentrate on creating the application, and Rails takes care of the details. Tens of thousands of deve......一起来看看 《Agile Web Development with Rails 4》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试