和标题相同,按照字典顺序输出全排列
来看一个样例
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
函数后容器中的元素将变为第一个排列。