问题:给出一个数,计算出其全排列结果。
回答:方法一:
#include <iostream>
#include <cstdio>
#include <algorithm>
#define maxN 4
using namespace std;
int main()
{
int p[maxN] = {-1};
for(int i=0; i<maxN; ++i)
{
p[i] = i+1;
}
do
{
for(int i=0; i<maxN; ++i)
{
printf("%d ",p[i]);
}
printf("
");
}while(next_permutation(p,p+maxN) );
return 0;
}
方法二:
#include <stdio.h>
#include <stdlib.h>
//#define maxN 10
#define maxN 4
void permutation(int n,int arry[],int cur)
{
if(cur == n)
{
int i=0;
for(; i<n; ++i)
{
printf("%d ",arry[i]);
}
printf("
");
return;
}
int iwhich=1;
for(;iwhich<=n;++iwhich)
{
bool bInArry=false;
int itmp=0;
for(;itmp<cur;++itmp)
{
if(iwhich == arry[itmp])
{
bInArry = true;
break;
}
}//is in?
if(false == bInArry)
{
arry[cur] = iwhich;
permutation(n,arry,cur+1);
}
}
}
int main()
{
int arry[maxN] = {-1};
permutation(maxN,arry,0);
return 0;
}