LeetCode 47. 全排列 II 终极剖析

1.给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

2.此题与 LeetCode 46.全排列相似,但46题中元素不重复,47题中含有重复元素.

3.解题方法 ; 递归 + 哈希表

4.解题思路: 首先创建全局变量 retList 来准备存储所有全排列数组

创建 helper 方法,用来递归

:

返回 retList ;

5.具体代码如下:

    List<List<Integer>> retList = new LinkedList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
//        借助 permute2Helper() 方法完成递归
//        首先传入的count 为 0(从 0 开始交换)
        permute2Helper(0,nums);
        return retList;
    }

    private void permute2Helper(int count, int[] nums) {
//        当count 换到最后一个时.说明一轮已经完成,记录到最终结果中
        if(count + 1 == nums.length){
            List<Integer> tmpList = new LinkedList<>();
            for (int i = 0; i < nums.length; i++) {
                tmpList.add(nums[i]);
            }
            retList.add(tmpList);
        }
//        使用 HashSet 去重
        Set<Integer> set = new HashSet<>();
        for (int i = count; i < nums.length; i++) {
//            添加成功,说明钙元素还未使用,if代码块
            if(set.add(nums[i])){
                swap(nums,count,i);
                permute2Helper(count + 1,nums);
                swap(nums,count,i);
            }
        }
    }
//    帮助完成交换
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    

此题考点: 1.递归终止条件;

                2.递归的理解;

                3.怎样去重.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值