方法一:暴力
#include<stdio.h> #include<stdlib.h> int m,n,a[10],sum=0; void check(void) { int i,add=0; for(i=0;i<n;i++) { add+=a[i]; } if(add==m)sum++; } int main(void) { int k; scanf("%d",&k); for(;k>0;k--) { sum=0; scanf("%d %d",&m,&n); if(m*n==0) { printf("0/n"); continue; } if(n==1) { printf("1/n"); continue; } for(a[0]=0;a[0]<=m;a[0]++) { for(a[1]=0;a[1]<=a[0];a[1]++) { if(n==2){check();continue;} for(a[2]=0;a[2]<=a[1];a[2]++) { if(n==3){check();continue;} for(a[3]=0;a[3]<=a[2];a[3]++) { if(n==4){check();continue;} for(a[4]=0;a[4]<=a[3];a[4]++) { if(n==5){check();continue;} for(a[5]=0;a[5]<=a[4];a[5]++) { if(n==6){check();continue;} for(a[6]=0;a[6]<=a[5];a[6]++) { if(n==7){check();continue;} for(a[7]=0;a[7]<=a[6];a[7]++) { if(n==8){check();continue;} for(a[8]=0;a[8]<=a[7];a[8]++) { if(n==9){check();continue;} for(a[9]=0;a[9]<=a[8];a[9]++) { if(n==10){check();continue;} } } } } } } } } } } printf("%d/n",sum); } return 0; } 方法二:递归。类似整数的划分
#include<stdio.h> int m,n; int fn(int n,int m) { if((n<1)||(m<1))return 0; if((n==1)||(m==1))return 1; if(n<m)return fn(n,n); if(n==m)return fn(n,m-1)+1; return fn(n,m-1)+fn(n-m,m); } int main(void) { int k; scanf("%d",&k); for(;k>0;k--) { scanf("%d %d",&m,&n); printf("%d/n",fn(m,n)); } return 0; }