Leetcode #47. Permutations II 全排列2 解题报告

1 解题思想

这道题,就是第二个去全排列了,我昨天也预告过了,没看过的先看下上一题的解法:
Leetcode # 46. Permutations 全排列 解题报告

这道题有什么不一样的么?上一道题的数组是不重复的,这一次的是可以重复的。

但我们输出的时候,是不能输出重复排列的,那怎么办?
首先说明我这次的代码是基于上一次修改的。改进的方式是交换的那一个策略,所以你需要先去上一篇读一下这个具体的方式。

因为有重复,所以我们每次交换的时候,对于每一个取值,只交换一次!
什么意思,对于序列【0,1,2,2,3,3,3,4,4,4,4.。。】,当我指针在0上,需要和后面的进行一一交换,但因为存在重复,所以只和1个1交换,只和1个2交换,只和1个3交换!

而具体在实现的时候,我使用一个HashSet,保证交换的时候一个取值只交换一次

嗯,这不是结束。。全排列还有题。。不止这一个,后面我再介绍新的解法

2 原题

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

3 AC解

public class Solution {
    /**
     * 这道题,其实好像用字典序也可以
     * */
    List<List<Integer>> list;
    public List<Integer> toList(int nums[]){
        List<Integer> list=new ArrayList<Integer>();
        for(int i=0;i<nums.length;i++)
            list.add(nums[i]);
        return list;
    }
    public void swap(int[] nums,int a,int b){
        int tmp=nums[a];
        nums[a]=nums[b];
        nums[b]=tmp;
    }
    public void dfs(int[] nums,int index){
        if(index==nums.length)
            list.add(toList(nums));
        Set<Integer> set = new HashSet<Integer>(); //因为有重复,所以每次交换之和一个出现相同的元素进行交换,可以排序实现,我这里使用Set来表示
        for(int i=index;i<nums.length;i++){
                if(set.contains(nums[i]))
                    continue;
                set.add(nums[i]);
                swap(nums,i,index);
                dfs(nums,index+1);
                swap(nums,index,i);
        }
    }
    //从第一个数开始,不停的与他之后的进行交换,中间有DFS
    //这道题关键在于DFS 看具体的介绍
    public List<List<Integer>> permuteUnique(int[] nums) {
      //  Arrays.sort(nums);
        list=new ArrayList<List<Integer>>();
        if(nums.length==0)
            return list;
        dfs(nums,0);
        return list;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值