全排列
什么是全排列???:例题进行讲解
例题:全排列
试题内容:
给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有’a’ < ‘b’ < … < ‘y’ < ‘z’,而且给定的字符串中的字母已经按照从小到大的顺序排列。
input
输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。
output
输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义:
已知S = s 1s 2…s k , T = t 1t 2…t k,则S < T 等价于,存在p (1 <= p <= k),使得 s 1 = t 1, s 2 = t 2, …, s p - 1 = t p - 1, s p < t p成立。
Sample Input
abc
Sample Output
abc
acb
bac
bca
cab
cba
题目思路:
递归回溯,搜索问题
1.超级好用的,STL中的全排列函数
2.DFS
解题方法
next_permutation
补充知识:
algorithm中:
按照字典升序:
next_permutation(start,end):
在数组中的使用:
do{
for(int i=0;i<n;i++) cout<<a[i];
printf("%\n");
}while(next_permutation(a,a+n));
//n表示对前几个进行全排列,如果写成next_permutation(a,a+2),对于123而言,全排列的结果就只有两个:123;213。
在string中的使用:
do{
cout<<s<<endl;
}while(next_permutation(s.begin(),s.end()));
注意:在使用next_premutation()前需要进行升序排列,否则会出现减少排列的结果。
按照字典降序:
prev_permutation(start,end)。
#include <cstdio>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string s;
int main(){
cin>>s;
int len = s.length();
do{
cout<<s<<endl;
}while(prve_permutation(s.begin(),s.end()));
return 0;
}
DFS
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 10;
char a[maxn];
char temp[maxn];
bool vis[maxn];
void dfs(int x,int len) {
if (x == len) printf("%s\n",temp);
for (int i = 0; i < len; i++) {
if (!vis[i]) {
temp[x] = a[i];
vis[i] = true;
dfs(x + 1, len);
vis[i] = false;
}
}
}
int main() {
scanf("%s", a);
int len = strlen(a);
memset(vis, 0, sizeof(vis));
dfs(0,len);
return 0;
}
}
勉励:
打卡第三天,加油!ヾ(◍°∇°◍)ノ゙
如果觉得我的文章对你有所帮助与启发,点赞给我个鼓励吧(づ ̄3 ̄)づ╭❤~
关注我和我一起共勉加油
吧!
如果文章有错误,还望不吝指教!