全排列
一般全排列,可以使用搜索的方法完成,这里我们介绍其函数的实现方式。
1. next_permutation()函数
next.permutation函数用于生成当前序列的下一个排列。它按照字典序对序列进行重新排列,如果存在下一个排列,则将当前序列更改为下一个排列,并返回 true;如果当前序列已经是最后一个排列,则将序列更改为第一个排列,并返回false。
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3};
cout << "Initial permutation: ";
for(int num : nums) {
cout << num << " ";
}
cout << endl;
// 生成下一个排列
while(next_permutation(nums.begin(), nums.end())) {
cout << "next permutation: ";
for(int num : nums) {
cout << num << " ";
}
cout << endl;
}
return 0;
}
输出结果
Initial permutation: 1 2 3
next permutation: 1 3 2
next permutation: 2 1 3
next permutation: 2 3 1
next permutation: 3 1 2
next permutation: 3 2 1
对于一个数组,如何实现字典序正序全排列?如下代码所示
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[] = {1, 2, 3};
// 输出当前的序列
for(int i = 0; i < 3 ; i ++ ) {
printf("%d ", a[i]);
}
cout << endl;
while(next_permutation(a, a + 3)) { // 直接变成当前序列全排序的下一个序列, 首先输出的
for(int i = 0; i < 3 ; i ++ ) { // 是123
printf("%d ", a[i]);
}
cout << endl;
}
return 0;
}
2. prev_permutation()函数
prev_permutation函数与next_permutation函数相反,它用于生成当前序列的上一个排列。它按照字典序对序列进行重新排列,如果存在上一个排列,则将当前序列更改为上一个排列,并返回true;如果当前序列已经是第一个排列,则将序列更改为最后一个排列,并返回false。
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {3, 2, 1};
cout << "Initial permutation: ";
for(int num : nums) {
cout << num << " ";
}
cout << endl;
// 生成下一个排列
while(prev_permutation(nums.begin(), nums.end())) {
cout << "Previous permutation: ";
for(int num : nums) {
cout << num << " ";
}
cout << endl;
}
return 0;
}
输出结果
Initial permutation: 3 2 1
Previous permutation: 3 1 2
Previous permutation: 2 3 1
Previous permutation: 2 1 3
Previous permutation: 1 3 2
Previous permutation: 1 2 3
对于一个数组,如何实现字典序倒序全排列?
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[] = {3, 2, 1};
// 输出当前的序列
for(int i = 0; i < 3 ; i ++ ) {
printf("%d ", a[i]);
}
cout << endl;
while(prev_permutation(a, a + 3)) {
for(int i = 0; i < 3 ; i ++ ) {
printf("%d ", a[i]);
}
cout << endl;
}
return 0;
}