码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer08

时间:2018-01-13 20:57:25      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:use   turn   多少   for   一个   class   int   台阶   pac   

package jianzhiOffer; /**  * 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级 的台阶总共有多少种跳法。  *   * @author user   * 思路:倾向于找规律的解法,f(1) = 1, f(2) = 2, f(3) = 3, f(4) = 5, 可以总结出f(n) =  * f(n-1) + f(n-2)的规律,但是为什么会出现这样的规 律呢?假设现在6个台阶,我们可以从第5跳一步到6,  * 这样的话有多少种方案跳到5就有多少种方案跳到6,另外我们也可以从4跳两步跳到6,跳到4有多少种方案的  * 话,就有多少种方案跳到6,其他的不能从3跳到6什么的啦,所以最 后就是f(6) = f(5) + f(4),所以f(n) =  * f(n-1) + f(n-2)  */ public class ch08 { public int JumpFloor(int target) { int first = 1; int second = 2; int result = 0; if (target <= 0) { return 0; } if (target == 1) { return 1; } if (target == 2) { return 2; } for (int i = 3; i <= target; i++) { result = first + second; first = second; second = result; } return result; } }


剑指offer08

标签:use   turn   多少   for   一个   class   int   台阶   pac   

原文地址:http://blog.51cto.com/12222886/2060633

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!