1. 程式人生 > >整數劃分問題(遞迴演算法)

整數劃分問題(遞迴演算法)

int q (int n, int m, int *out, int length)
{
 if(n<1||m<1)
  return 0;
 if(n==1||m==1)
 {
  if(n==1)
  {
   out[length] = n;
   print(out, length+1);
  } 
  else //m==1
  {
   for(int k=0;k<n;k++)
   {
    out[length++] = m;
   }
   print(out,length);
  }
  return 1;
 }
 if(n==m)
 {
  //one element
  out[length] = m;
  print(out,length+1);
 
  int temp = q(n,m-1,out,length);
  return 1 + temp;
 }
 if(n<m)
 {
  int temp = q(n,n,out,length);
  return temp;
 }
 
 out[length] = m;
 int temp1 = q(n-m,m,out,length+1);