字典序输出全排列

和标题相同,按照字典顺序输出全排列

来看一个样例

1~3的全排列  :
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

如上图

下面看代码

代码一

 利用dfs直接搜索

#include <bits/stdc++.h>
using namespace std;
const int N=10;
int s[N];bool st[N];
int t=0;
void dfs(int n)
{
    if(n==t){
        for(int i=1;i<t;i++)cout<<s[i]<<' ';
        cout<<s[t]<<endl;
    }
    for(int i=1;i<=t;i++)
    {
        if(!st[i])
        {
            s[n+1]=i;
            st[i]=true;
            dfs(n+1);
            st[i]=false;
        }  
    }
}
int main() {
    memset(st,false,sizeof st);
    cin>>t;
    dfs(0);
}

代码二

 利用<algorithm>库函数

#include <iostream>
#include <algorithm>
using namespace std;
int a[10];
int main()
{
   int n;
   cin >> n;
   for(int i=1;i<=8;i++)a[i]=i;
   do{
        for(int i=1;i<8;i++)
        {
            cout << a[i] << " ";
        }
        cout << a[8] << endl;
   }while(next_permutation(a+1,a+9));
   return 0;
}

详讲

next_permutation 函数是 C++ 标准库中的一个函数,定义在 <algorithm> 头文件中。它用于生成容器中元素的下一个排列。

函数原型如下:

cpp

复制

template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last);

参数 first 和 last 是迭代器,表示容器中要生成下一个排列的元素范围。first 表示元素范围的起始位置,last 表示元素范围的结束位置(不包含在范围内)。

函数的返回值是一个布尔值,表示是否成功生成下一个排列。如果生成了下一个排列,则返回 true,否则返回 false

next_permutation 函数按照字典序生成容器中元素的下一个排列,并将结果保存在容器中。如果容器中的元素已经是最后一个排列,调用 next_permutation 函数后容器中的元素将变为第一个排列。

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

非黑皆白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值