Shirlies
宁静专注认真的程序媛~

题目

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

链接

http://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387?tpId=13&tqId=11162&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

答案

一个台阶:1

两个台阶:2

三个台阶:1 + 2 + 1 = 4

四个台阶:1 + 2 + 4 + 1 = 8

...

N个台阶:f(1) + f(2) + ... + f(n - 1) + 1 = 2^0 + 2^1 + 2 ^2 + ... + 2^(n-2) + 1 = 2 ^ (n - 1) - 1 + 1 = 2 ^ (n - 1)

代码

 1 class Solution {
 2 public:
 3     int jumpFloorII(int number) {
 4         if(number == 1){
 5             return 1;
 6         }
 7         
 8         long long ans = 1 << (number - 1);
 9         
10         return ans;
11     }
12 };
View Code

 

posted on 2016-08-16 16:42  Shirlies  阅读(180)  评论(0)    收藏  举报