题目:传送门
题意:
给一个数字,按照字典序从小到大的顺序输出改数字的所有全排列。
题解:
纯考全排列,练习一下STL里面的next_permutation。顺带复习一下prev_permutation和reverse。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
using namespace std;
int main(void){
string str;
cin>>str;
sort(str.begin(),str.end());
do{
cout<<str<<endl;
}while(next_permutation(str.begin(),str.end()));
return 0;
}
如果改一下题目,按照字典序从大到小:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
using namespace std;
int main(void){
string str;
cin>>str;
sort(str.begin(),str.end());
reverse(str.begin(),str.end());//reverse 还可以反转vector
do{
cout<<str<<endl;
}while(prev_permutation(str.begin(),str.end()));
return 0;
}
本文介绍了一种使用STL库中的next_permutation和prev_permutation函数实现数字全排列的方法,能够按照字典序从小到大或从大到小输出所有可能的排列组合。通过示例代码展示了如何对字符串进行排序和反转,以满足不同排列顺序的需求。

被折叠的 条评论
为什么被折叠?



