问题描述:对n个元素进行全排列,列出所有情况,例如1,2,3三个数字会得到1 2 3,1 3 2,2 1 3,2 3 1,3 1 2,3 2 1这6中情况
思路:设n为元素个数,元素集合为R(r1,r2,r3…rn),计算方法为Perm(n)
当n = 1时,则只有一种情况 r;
当n > 1时,则有(r1)Perm(R1),(r2)Perm(R2),(r3)Perm(R3) … … (rn)Perm(Rn)
以1,2,3为例全排列,共有以下排列:
1 Perm(2,3) 即:以1为前缀的所有组合
2 Perm(1,3) 即:以2为前缀的所有组合
3 Perm(2,3) 即:以3为前缀的所有组合
注:Perm(k,m)利用递归的思想即可不断划分前缀,直到只剩下1个元素,则只有一种情况,即为找到了一种排列。
#include<iostream>
using namespace std;
void perm(int list[], int k, int m){
if(k == m){
for(int i = 0; i <= m; i++){
//输出list
cout << list[i];
}
cout << endl;
} else {
for(int i = k; i <= m; i++){
swap(list[k], list[i]);
perm(list, k + 1, m);
swap(list[k], list[i]); //还原
}
}
}
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
int main(){
int a[3] = {1, 2, 3};
perm(a, 0, 2);
return 0;
}
思考过程: