数字123的全排列,应用深度优先搜索原理
#include<iostream>
using namespace std;
int a[4], book[4];
void permulation(int step) {
if (step == 4) {
for (int i = 1; i <= 3; i++) {
cout << a[i] << " ";
}
cout << endl;
return;
}
for (int i = 1; i <= 3; i++) {
if (book[i]== 0) {
a[step] = i;
book[i] = 1;
permulation(step + 1);
book[i] = 0;
}
}
return;
}
int main() {
permulation(1);
return 0;
}
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1到任意数字的全排列
#include<iostream>
#include<vector>
using namespace std;
void permulation(int step,int num) {
static vector<int> a(num+1, 0), book(num+1,0); //此处static不可忽略,只初始化依次,初始
值为0