找出1到n所有不重複的排列,即n的全排列。
阿新 • • 發佈:2019-01-08
解法一:
#include <iostream>
#include <vector>
using namespace std;
//列印結果
void printSolution(const vector<int> &v)
{
for (vector<int>::const_iterator it = v.begin();it != v.end();++it)
{
cout<<*it<<' ';
}
cout<<endl;
}
//構造遞迴函式,放第i個位置的數
void fun(vector<int> &v, vector<int> &f, int i)
{
int n = v.size();
for (int j=1;j<=n;++j)
{
//如果數j沒有出現過,則第i個位置放j
if (!f[j-1])
{
f[j-1] = 1;
v[i] = j;
//如果數全部放完,則列印結果
if (i == n-1)
{
printSolution(v);
}
else
{
fun(v, f, i+1);
}
//回溯
f[j-1] = 0;
}
}
}
int main()
{
cout<<"輸入n的值:";
int n;
cin>>n;
if (n<1)
{
cout<<"輸入有誤!"<<endl;
exit(1);
}
//記錄全排列
vector<int > v(n,0);
//f[i]記錄i+1是否出現過
vector<int> f(n,0);
fun(v, f, 0);
return 0;
}
執行結果: