爬楼梯问题的解决

// 爬楼梯问题.cpp : 定义控制台应用程序的入口点。
//time:2013.9.23
//author:tiance
//function:implements palouti algorithms

 

 

#include "stdafx.h"
#include <process.h>
#include <iostream>
using namespace std;

 

 

 

//前提,一次只能一步或者两步
//解:因为1阶台阶,1种走法;
// 2阶台阶,有1+1、2,共2种走法;
// 3阶台阶,有1+1+1、1+2、2+1,共3种走法,即1+2=3;
// 4阶台阶,有1+1+1+1、1+1+2、1+2+1、2+1+1、2+2,共5种走法,即2+3=5;
// 5阶台阶,有1+1+1+1+1、1+1+1+2、1+1+2+1、1+2+1+1、2+1+1+1、1+2+2、2+1+2、2+2+1,共8种走法3+5=8;
// ……
// 所以6阶台阶,有5+8=13种;
//7阶台阶,有8+13=21种;8阶台阶,有13+21=34种;
// 结论:有n阶台阶,从下向上走,若每次只能跨过1级或2级,走法的规律为1,2,3,5,8,13,21……,
//即a1=1,a2=2,an=an-1+an-2

//有10阶台阶,小明从下向上走,若每次只能跨过1级或2级或3级,他走上去共有多少种方法?
// 解:
// 解:因为1阶台阶,1种走法;
// 2阶台阶,有1+1、2,共2种走法;
// 3阶台阶,有1+1+1、1+2、2+1、3,共4种走法;
// 4阶台阶,有1+1+1+1、1+1+2、1+2+1、2+1+1、2+2、1+3、3+1,共7种走法,即1+2+4=7;
// 5阶台阶,有1+1+1+1+1、1+1+1+2、1+1+2+1、1+2+1+1、2+1+1+1、1+2+2、2+1+2、2+2+1、1+1+3、1+3+1、3+1+1、2+3、3+2,共13种走法2+4+7=13;
// ……
// 所以6阶台阶,有4+7+13=24种;7阶台阶,有7+13+24=44种;8阶台阶,有13+24+44=81种;9阶台阶,有24+44+81=149种;10阶台阶,有44+81+149=274种.
// 结论:有n阶台阶,从下向上走,若每次只能跨过1级或2级或3级,走法的规律为1,2,4,7,13,24,44,……,即
//a1=1,a2=2,a3=4,an=an-1+an-2+an-3

 

 

 


long GetJumpFloorMethodCount(int floor)
{
 if (floor<0)
 {
  return -1;
 }
 if (floor==0)
 {
  return 0;
 }
 if (floor==1)
 {
  return 1;
 }
 if (floor==2)
 {
  return 2;
 }
 else
 {
  return GetJumpFloorMethodCount(floor-1)+GetJumpFloorMethodCount(floor-2);
 }
}

 

 

 


int _tmain(int argc, _TCHAR* argv[])
{
 for(int index=0;index<30;++index)
 {
  long ret;
     ret=GetJumpFloorMethodCount(index);
  cout<<index<<"<------->";
  cout<<ret<<endl;
 }
 
 system("pause");
 return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值