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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值