剑指offer84:包含重复元素集合的全排列

题目:
给定一个可包含重复数字的整数集合 nums ,按任意顺序 返回它所有不重复的全排列。
1.输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
2.输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
分析:
该题与83题的不同点在于如果集合中有重复的数字,那么交换集合中重复的数字得到的全排列是同一个全排列。
思路与83题基本一致,不再赘述,只说不同之处。
当处理到全排列第i个数字时,如果已经将某个值为m的数字交换为排列的第i个数字,那么遇到其他值为m的数字就跳过。
例如nums为 2,1,1,处理排列下标为0的数字时,将第一个数字1和数字2交换后,就每必要将第二个数字1和数字2交换了,将第一个数字1和数字2交换后,得到1,2,1,接着处理排列的第2个数字和第3个数字,这样就能生成两个排列1,2,1 和 1,1,2。
代码:

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class PermuteUnique {
    public static void main(String[] args) {
        PermuteUnique permuteUnique = new PermuteUnique();
        int[] nums = {1,1,2};
        List<List<Integer>> lists = permuteUnique.permuteUnique(nums);
        System.out.println(lists);
    }
        public List<List<Integer>> permuteUnique(int[] nums) {
//        当函数helper生成的排列的下标为i的数字时,下标从0到i-1的数字都已经被选定
            List<List<Integer>> result = new LinkedList<>();
            helper(nums,0,result);
            return result;
        }

        private void helper(int[] nums, int i, List<List<Integer>> result) {
            if (i == nums.length){
                LinkedList<Integer> permutation = new LinkedList<>();
                for (Integer num : nums) {
                    permutation.add(num);
                }
                result.add(permutation);
            }else{
            //用来保存已经交换到排列下标为i的位置的所有值,只有当一个数值之前没有被交换到第i位才做交换否则直接跳过。
                Set<Integer> set = new HashSet<>();
                for (int j = i; j < nums.length; j++) {
                    if (!set.contains(nums[j])){
                        set.add(nums[j]);
                        swap(nums,i,j);
                        helper(nums,i+1,result);
//                由于之前已经交换了数组中的两个数字,修改了排列的状态,在函数退出之前需要清除对排列状态的修改,因此交换之前交换的两个数字
                        swap(nums,i,j);
                    }

                }
            }
        }
        private void  swap(int[] nums,int i,int j){
            if (i!=j){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙崎流河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值