之前没有注意到,原来C++ algorithm中有全排列函数,着实简单,而且包含元素可重复情况。
#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\t",p[i]);
}
printf("\n");
}while(next_permutation(p,p+maxN) );
return 0;
}
不用STL要考虑递归了,下面代码没有考虑元素重复,只是简单的1-N的全排列,由小到大输出。
#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\t",arry[i]);
}
printf("\n");
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;
}
很自然的求子集也是同样的递归套路。