参考《算法竞赛入门经典》,用递归枚举时。枚举排列时,到cur==n,即够n个元素的时候,才终止递归。枚举子集,则枚举到0-n个元素都要进行操作。
一:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int maxn=20;
int P[]={0,1};
int A[maxn];
void print_permutation(int n,int h,int *A,int *P,int cur)
{
int i;
if(cur==n)
{
for(i=0;i<n;i++) printf("%d",A[i]);
printf("\n");
}
else for(i=0;i<2;i++)
{
int c=0;
for(int j=0;j<cur;j++) if(A[j]==P[i]) c++;
if(P[i] && c<h || !P[i] && c<n-h)
{
A[cur]=P[i];
print_permutation(n,h,A,P,cur+1);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("729.txt","r",stdin);
#endif
int N;
scanf("%d",&N);
while(N--)
{
int n,h;
scanf("%d%d",&n,&h);
print_permutation(n,h,A,P,0);
if(N) printf("\n");
}
return 0;
}
二:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=20;
int A[maxn];
int main()
{
#ifndef ONLINE_JUDGE
freopen("729.txt","r",stdin);
#endif
int N;
scanf("%d",&N);
while(N--)
{
int n,h;
scanf("%d%d",&n,&h);
int i;
for(i=0;i<n-h;i++) A[i]=0;
for(;i<n;i++) A[i]=1;
do
{
for(i=0;i<n;i++) printf("%d",A[i]);
printf("\n");
}while(next_permutation(A,A+n));
if(N) printf("\n");
}
return 0;
}