C++/python描述 AcWing 94. 遞歸實作排列型枚舉
把 1∼n 這 n 個整數排成一行後随機打亂順序,輸出所有可能的次序。
輸入格式
一個整數 n。
輸出格式
按照從小到大的順序輸出所有方案,每行 1 個。
首先,同一行相鄰兩個數用一個空格隔開。
資料範圍
輸入樣例:
3
輸出樣例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
算法實作一 C++
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n,res[10] = {0};
cin >> n ;
for(int i = 0 ; i < n; i++) res[i] = i+1;
do{
for(int i = 0 ; i < n ;i++)
cout<<res[i] <<" ";
cout<<endl;
}while(next_permutation(res,res+n));
return 0;
}
算法實作二 C++
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n,res[10] = {0},m=1;
cin >> n ;
for(int i = 0; i < n; i++) res[i] = i+1;
for(int i = 1; i <= n; i++) m *= i;
for(int i = 0 ; i < n ;i++)
cout<<res[i] <<" ";
cout<<endl;
m--;
while(m--){
int i = n-1;
while(i && res[i] < res[i-1]) i--;
int j = i;
while(j + 1 < n && res[j+1] > res[i-1]) j++;
swap(res[i-1],res[j]);
reverse(res+i,res+n);
for(int i = 0 ; i < n ;i++)
cout<<res[i] <<" ";
cout<<endl;
}
return 0;
}
算法實作三 Python
from itertools import permutations
n = int(input())
res = [i+1 for i in range(n)]
for item in permutations(res):
for d in item:
print(d,end=' ')
print('')
算法實作四 Python
from itertools import permutations
n = int(input())
res = [i+1 for i in range(n)]
m = 1
for i in range(n):
m *= (i+1)
for item in res:
print(item,end=' ')
print(' ')
m -= 1
while m:
i = n - 1
while n > 0 and res[i] < res[i-1]:
i -= 1
j = i
while j+1 < n and res[i-1] < res[j+1]:
j += 1
res[i-1],res[j] = res[j],res[i-1]
res[i:] = reversed(res[i:])
for item in res:
print(item,end=' ')
print('')
m -= 1