全排列
next_permutation()函数
next_permutation 函数用于生成当前序列的下一个排序。它按照字典序对序列进行重新排序,如果存在下一个排列,则将当前序列更改为下一个排列,并返回true; 如果当前序列已经是最后一个排序,则将序列更改为第一个排列,并返回false.
vertor<int> nums = {1, 2, 3};
cout << "Initial permutation: ";
for(int num : nums){
cout << num << " ";
} cout << endl;
//生成下一个排列
while(nevt_permutation(nums.begin(), nums.end()){
cout << "Next permutation: ";
for(int num : nums){
cout << num << " ";
}
cout << endl;
}
_ _ |
---|
123 |
132 |
213 |
312 |
321 |
prev_permutation() 函数
prev_permutation 函数与 next_permutation 函数相反,它用于生成当前序列的上一个排序。它按照字典对序列进行重新排序,如果存在上一个排列,则将当前序列更改为上一个排序,并返回true; 如果当前序列已经是第一个排序,则将序列更改为最后一个排序,并返回false.
vertor<int> nums2 = {3, 2, 1};
cout << "Initial permutation: ";
for(int num : nums2){
cout << num << " ";
} cout << endl;
//生成上一个排列
while(prev_permutation(nums2.begin(), nums2.end()){
cout << "Prevous permutation: ";
for(int num : nums2){
cout << num << " ";
}
cout << endl;
}
321 |
---|
312 |
231 |
213 |
132 |
123 |
实例
题目
全排列
next_permutation()函数
next_permutation 函数用于生成当前序列的下一个排序。它按照字典序对序列进行重新排序,如果存在下一个排列,则将当前序列更改为下一个排列,并返回true; 如果当前序列已经是最后一个排序,则将序列更改为第一个排列,并返回false.
vertor<int> nums = {1, 2, 3};
cout << "Initial permutation: ";
for(int num : nums){
cout << num << " ";
} cout << endl;
//生成下一个排列
while(nevt_permutation(nums.begin(), nums.end()){
cout << "Next permutation: ";
for(int num : nums){
cout << num << " ";
}
cout << endl;
}
_ _ |
---|
123 |
132 |
213 |
312 |
321 |
prev_permutation() 函数
prev_permutation 函数与 next_permutation 函数相反,它用于生成当前序列的上一个排序。它按照字典对序列进行重新排序,如果存在上一个排列,则将当前序列更改为上一个排序,并返回true; 如果当前序列已经是第一个排序,则将序列更改为最后一个排序,并返回false.
vertor<int> nums2 = {3, 2, 1};
cout << "Initial permutation: ";
for(int num : nums2){
cout << num << " ";
} cout << endl;
//生成上一个排列
while(prev_permutation(nums2.begin(), nums2.end()){
cout << "Prevous permutation: ";
for(int num : nums2){
cout << num << " ";
}
cout << endl;
}
321 |
---|
312 |
231 |
213 |
132 |
123 |
实例
题目
给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。我们假设对于小写字母有“a’<.
<'v<z,而且给定的字符串中的字母已经按照从小到大的顺序排列。
输入格式
输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。
输出格式
输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义已知S= siS2…Sk,T = ttz…tk,则S<等价于,存在p(1<p< k),使得s = t,s2=t2,…, Sp-1 = tp-l,Sp < t成立。
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
getline(cin, str);
int len = str.size();
sort(str.begin(), str.end());
bool tag = true;
while (tag) {
cout << str << endl;
tag = next_permutation(str.begin(), str.end());
}
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
getline(cin, str);
int len = str.size();
sort(str.begin(), str.end());
bool tag = true;
while (tag) {
cout << str << endl;
tag = next_permutation(str.begin(), str.end());
}
return 0;
}