力扣(LeetCode)47

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

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

题目地址:

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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Remote

Remote

Jason Fried、David Heinemeier Hansson / Crown Business / 2013-10-29 / CAD 26.95

The “work from home” phenomenon is thoroughly explored in this illuminating new book from bestselling 37signals founders Fried and Hansson, who point to the surging trend of employees working from hom......一起来看看 《Remote》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具