蓝桥杯必看 【手撕模板】三分钟搞懂 <数字排序问题 + STL>

本文详细介绍了如何使用深度优先搜索(DFS)和STL中的next_permutation函数解决LeetCode上的排列问题。通过示例代码展示了两种方法,包括常规的DFS回溯策略和STL库的高效排列生成。内容涵盖了C++实现的细节和代码解释,帮助读者深入理解排列算法。
摘要由CSDN通过智能技术生成

LeetCode模板题

补充一、排列

在这里插入图片描述

方法一、(常规)dfs + 回溯

Ps:

回溯一定要注意的是 恢复现场
利用 递归搜索树 求解

#include<iostream>

using  namespace std;
const int N = 10;

int n ;
bool st[N]={0};//储存状态
int nums[N]={0};//储存数据
void dfs(int cnt)

{
    if(cnt > n) 
    {
        for(int i = 1 ;i <= n; i ++  )  cout <<nums[i]<<' ';
        cout << endl;
    }
        
    else
    {
        for(int i = 1; i <= n ; i ++ )
        {
            if(!st[i])//依次找到没有使用过的数
            {
                st[i] = 1;
                nums[cnt] = i;
                dfs(cnt + 1);
                st[i] = 0;//恢复场景
            }
        }
    }
    
}

int main()
{
    
    cin >> n;
    
    dfs(1);
    
    return 0;
}

补充二、(STL)next_permutation

[点击跳转->next_permutation详解]

由上文我们可知 next_permutation 函数可以对 ret 数组进行指定操作
得到目前数字 的 下一个 字典序 yyds

(https://blog.csdn.net/GuLeng______/article/details/122953769?spm=1001.2014.3001.5502)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    int n;  cin >>n;
    vector<int> ret ;
    for(int i = 1;i <= n ; i ++)    ret.push_back(i);//读入 1 ~ n
    
    do
    {
        for(int i = 0;i < n ; i ++) cout<<ret[i]<<' ';
        cout<<endl;
        
    }while(next_permutation(ret.begin(), ret.end()));
    //**因为该函数在本身是最大字典序的时候会返回fasle** 
    
    
    
    return 0;
}

例题二、数字排列

话不多说直接上STL

class Solution {
public:
    vector<vector<int>> permutation(vector<int>& nums) 
    {
        sort(nums.begin(), nums. end());
        
        vector<vector<int>>ret ;//定义一个存放 数组的 数组 所以10行才可以 push_back 数组
        do
        {
            ret.push_back(nums);//将原数组 放入vector
        }while(next_permutation(nums.begin(),nums.end()));
        return ret;
    }
};
  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值