一. 分析
设 R = {r1, r2, …, rn} 是要进行排列的 n 个元素,Ri = R - {ri}。Perm(X) 为 X 的全排列。
- 当 n = 1 时,Perm( R ) = ( { r } ),其中 r 是集合 R 中唯一的元素;
- 当 n > 1 时,Perm( R ) = ( r1 )Perm( R1 ) + ( r2 )Perm( R2 ) + … + ( rn )Perm( Rn )。
即只要将每个元素与第一个元素交换(作为“前缀”),剩下的不包括这个元素的子序列再将它的每一个元素与子序列的第一个元素交换,直到剩下的子序列中只有一个元素时,此时的数组排列就是全排列中的一种。
二. 例子
求解数组 { 1, 2, 3 } 的全排列,输出结果:123、132、213、231、321、312
三. 代码
/* 求解 {1, 2, 3 } 的全排列 */
#include <iostream>
using namespace std;
void swap(int &a,int &b) {
int temp = a;
a = b;
b = temp;
}
void perm(int list[], int low, int high) {
// 当low == high时,list 就是全排列中的一种,输出 list
if(low == high) {
for(int i = 0; i <= low; i++) {
cout << list[i];
}
cout << endl;
}
else {
for(int i = low; i <= high; i++) { // 将每个元素与第一个元素交换
swap(list[i], list[low]);
perm(list, low + 1, high); // 交换后得到子序列,再求子序列的全排列
swap(list[i], list[low]); // 将元素位置复原
}
}
}
int main() {
int list[] = { 1, 2, 3 };
perm(list, 0, 2);
return 0;
}