首页 > 其他 > 详细

青蛙跳台阶

时间:2019-11-16 00:19:13      阅读:105      评论:0      收藏:0      [点我收藏+]

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

 

分析:假定跳n级台阶的方法是关于n的函数F(n),现在要跳n级台阶,如果最后一次跳了1步,那么前面的(n-1)级有F(n - 1)种跳法;如果最后一次跳了两步,则前面的(n - 2)级有F(n - 2)种跳法,即F(n) =  F(n - 1) +  F(n - 2),n  >  2。(斐波那契数列)

 1 namespace JianZhiOffer
 2 {
 3     class JumpFloor
 4     {
 5         public int jumpFloor(int number)
 6         {
 7             // write code here
 8             int one = 1;
 9             int two = 2;
10             int three = 0;
11 
12             if (number < 1)
13             {
14                 return 0;
15             }
16             else if (number == 1)
17             {
18                 return 1;
19             }
20             else if (number == 2)
21             {
22                 return 2;
23             }
24             else
25             {
26                 //return (jumpFloor(number - 1) + jumpFloor(number - 2));
27                 for (int i = 3; i <= number; i++)
28                 {
29                     three = one + two;
30                     one = two;
31                     two = three;
32                 }
33                 return three;
34             }
35         }
36     }
37 }

 

青蛙跳台阶

原文:https://www.cnblogs.com/xiaolongren/p/11870248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!