/*全排列問題C++代碼
輸入:全排列元素數量 n
n個需要排列的字符
輸出:該n個字符的全排列序列
*/
#include <iostream>
using namespace std;
void swap(int &a, int &b) { //交換
int temp = a;
a = b;
b = temp;
}
void Perm(char list[], int low, int high) { //遞歸函數
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]); //把第low個元素和第i個元素交換
Perm(list, low + 1, high); //對子序列list[low+1]~list[high]執行遞歸排列操作
swap(list[i], list[low]); //將之前交換的兩個元素換回來
}
}
}
int main() {
int n;
char list[100];
cout << "Input the number of elements for Full Permutation: ";
cin >> n; //輸入排列字符的數量
cout << "\nInput: ";
for (int i = 0; i < n; i++)
cin >> list[i]; //輸入n個需要排列的字符
cout << "\nOutput:" << endl;
Perm(list, 0, n - 1);
cout << endl;
return 0;
}