ITvsET

smiley

帮助别人解决了一个技术题

     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;
}

posted on 2011-05-04 22:21 天一程 阅读(145) 评论(0)  编辑 收藏 引用 所属分类: 数据结构算法