如何在 C++ 中使用 STL 生成数组的所有逆向排列?
在本节中,我们将介绍如何在 C++ 中使用 STL 生成所有逆向排列。一些数字(如 (1, 2, 3))的正向和逆向排列如下所示 −
正向排列
1, 2, 3 1, 3, 2 2, 1, 3 2, 3, 1 3, 1, 2 3, 2, 1
逆向排列
3, 2, 1 3, 1, 2 2, 3, 1 2, 1, 3 1, 3, 2 1, 2, 3
我们将使用 previous_permutation() 函数来获取结果
算法
getPermutation(arr, n)
Begin sort arr reverse the arr repeat print array elements until the previous permutation calculation is not completed End
示例
#include<iostream>
#include <algorithm>
using namespace std;
void disp(int arr[], int n){
for(int i = 0; i<n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
void getPermutation(int arr[], int n) {
sort(arr, arr + n);
reverse(arr, arr+n);
cout << "Possible permutations: \n";
do{
disp(arr, n);
}while(prev_permutation(arr, arr+n));
}
int main() {
int arr[] = {11, 22, 33, 44};
int n = sizeof(arr) / sizeof(arr[0]);
getPermutation(arr, n);
}输出
Possible permutations: 44 33 22 11 44 33 11 22 44 22 33 11 44 22 11 33 44 11 33 22 44 11 22 33 33 44 22 11 33 44 11 22 33 22 44 11 33 22 11 44 33 11 44 22 33 11 22 44 22 44 33 11 22 44 11 33 22 33 44 11 22 33 11 44 22 11 44 33 22 11 33 44 11 44 33 22 11 44 22 33 11 33 44 22 11 33 22 44 11 22 44 33 11 22 33 44
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP