三种解法解含重复数字的全排列

博客介绍了LeetCode 47题的全排列II问题,提供了三种解法:一是通过交换改变首数字并递归排列;二是使用map标记数字是否已出现;三是从map中选择未使用的非重复数字进行排列。每种解法都详细解释了思路,并附有提交结果。
摘要由CSDN通过智能技术生成
LeetCode 47 全排列II

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

示例:

输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii

解法一

每次让一个数字做为首数字,剩下的递归排列。通过swap来改变首数字。
依次将待排列的集合规模变小,若某一个数字做过首字符则跳过。

如 1 2 2 3
先让1做第一个数字, 剩下子序列2 2 3进行递归
对2 2 3进行排列
可得 1 2 2 3、1 2 3 2 、1 3 2 2
当st=1,i=2时 nums[st]=2,nums[st]=2 此时进入isSwap函数判断,st=1,end=i=2,再nums[st]~nums[end-1]中出现了nums[end]的数字,说明nums[end]已经在st、st+1…,end-1位置中出现过,无需重复排列,所以continue。

class Solution {
   
public:
    void swap(int &a,int &b){
   
        int tmp=a;
        a=b;
        b=tmp;
    }
    bool isSwap(vector<int>& nums,int st,int end){
   
        for(int i=st;i<end;i++){
   
            if(nums[i]==nums[end]){
   
                return false;
            }
        }
        return true;
    }
    void  curusion(int st,vector<int>& nums,int numsSize,vector<vector<int>>& res,vector<int> & tmp){
   
        if(st==numsSize){
   
            for(int i=0;i<numsSize;i++){
   
                tmp.push_back
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值