具体做法可参照Matrix67大牛的博客http://www.matrix67.com/blog/archives/266
View Code
#include<cstdio> #include<string.h> #include<iostream> using namespace std; int up,n,k,sum; void test(int row,int ld,int rd,int cnt,int now) { if(now>n) return; if(cnt<k) { int pos=up&(~(ld|rd|row)); int p; while(pos) { p=pos&(-pos); pos=pos-p; test(row+p,(ld+p)<<1,(rd+p)>>1,cnt+1,now+1); } test(row,ld<<1,rd>>1,cnt,now+1); } else sum++; } int main() { while(~scanf("%d%d",&n,&k)) { up=(1<<n)-1; sum=0; test(0,0,0,0,0); printf("%d\n",sum); } return 0; }