Climbing Stairs

题目:

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

解析:

设 f(n) 表示爬 n 阶楼梯的不同方法数,为了爬到第 n 阶楼梯,有两个选择:
• 从第 n − 1 阶前进 1 步;
• 从第 n − 1 阶前进 2 步;

因此,有 f(n) = f(n − 1) + f(n − 2)。

这是一个斐波那契数列。

方法 1,递归,太慢;方法 2,迭代。

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         int prev = 0;
 5         int cur = 1;
 6         for(int i = 1; i <= n ; ++i){
 7             int tmp = cur;
 8             cur += prev;
 9             prev = tmp;
10         }
11         return cur;
12     }
13 };

 

posted on 2015-11-20 09:18  已停更  阅读(155)  评论(0编辑  收藏  举报