LeetCode70 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? (Easy)

分析:

经典的爬楼梯问题,对于第n阶可以从n - 1阶跳一步上来,也可以从n - 2阶跳两步上来,设dp[n]为到第n阶的方案数,

则dp[n] = dp[n - 1] + dp[n - 2]。

不过实现的时候采用自底向上的方式,不要用递归(大量重复计算)。

也算是一道动态规划的入门题吧。

代码:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         if (n == 1) {
 5             return 1;
 6         }
 7         if (n == 2) {
 8             return 2;
 9         }
10         int a = 1, b = 2, c = a + b;
11         for (int i = 3; i <= n; ++i) {
12             c = a + b;
13             a = b;
14             b = c;
15         }
16         return c;
17     }
18 };

 

posted @ 2016-09-22 21:56  wangxiaobao1114  阅读(104)  评论(0编辑  收藏  举报