4.1递归和排序
程序员文章站
2022-07-07 10:40:22
...
C++
#include <bits/stdc++.h>
using namespace std;
int n;
int a[15], cnt = 0;
void prem(int begin) {
if (begin == n + 1) {
cnt++;
for (int i = 1; i <= n; i++) {
cout << a[i] << " ";
}
cout << endl;
return;
}
for (int i = begin; i <= n; i++) {
swap(a[begin], a[i]);
prem(begin + 1);
swap(a[begin], a[i]);
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
a[i] = i;
prem(1);
cout << cnt << endl;
return 0;
}
Python
n = int(input())
arr = [i for i in range(1, n + 1)]
def perm(begin):
if begin == n:
for i in arr[:-1]:
print(i, end=' ')
print(arr[-1])
return
for i in range(begin, n):
arr[begin], arr[i] = arr[i], arr[begin]
perm(begin + 1)
arr[begin], arr[i] = arr[i], arr[begin]
perm(0)