幫助別人解決了一個技術題

Oh,yeah!電腦上顯示的結果正確的時候,心情有點小激動!畢竟花了自己一個多小時的時間解決了,其實問題困擾了自己一天。自己開始想的各種算法都不怎麼好實現,最後無奈之下,自己潛意識的感覺這與排列組合算法有關,偶果斷的去搜了下排列組合的算法,讀了下,思路至少有點啓發,但是腦子有點亂,看了下《拯救小兔》,計劃看完後完成那個題目和自己的漢諾塔遊戲,結果那個題目還是解決了,下面貼下題目和代碼:(路過的各位大俠,如果有好的想法,也交流共享哈~)

題目:

n = 3
1: 1 1 1
2: 1 2     // 2 1 is considered the same solution
3: 3
n = 5
1: 1 1 1 1 1
2: 1 1 1 2
3: 1 1 3
4: 1 2 2
5: 1 4
6: 2 3
7: 5
就是 用戶輸入一個數字 就分解成上述的東西 上至下的順序由長度決定 左到右由 數字大小決定

 


偶的代碼:(用了回溯的算法,遞歸的思想,每次求最後一個數字)
#include <stdio.h>
#include <malloc.h>

int minlast(int sum,int count)
{
 if(sum%count==0)
  return sum/count;
 else
  return sum/count+1;
}

int maxlast(int sum,int count)
{
 return sum-(count-1);
}

int min(int a,int b)
{
 if(a<=b)
  return a;
 else
  return b;
}

void getlast(int sum,int count,int lastcurrent,int a[],int Count)
{
 static k=0;
 a[count]=lastcurrent;                 //保留上次的最後的一個字符
 int i=0;
 if(count==1 || count==0)
 {
  if(count==1)
   a[count-1]=sum;
  printf("/n%d: ",++k);
  for(i=0;i<Count;i++)
   printf("%d ",a[i]);  
 }
 else
 {
  for(i=min(lastcurrent,maxlast(sum,count))
   ;i>=minlast(sum,count);i--)
   getlast(sum-i,count-1,i,a,Count);
 }
}


int main(void)
{
 int a,i,j;
 printf("Please Enter the number: ");
 scanf("%d",&a);

 int *b=(int*)malloc(a*sizeof(int));

 printf("After Computing:");

 
 for(i=a;i>=1;i--)
  for(j=maxlast(a,i);j>=minlast(a,i);j--)
  {
   getlast(a-j,i-1,j,b,i);
  }
  return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章