LeetCode之“动态规划”: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?

  做这道题容易陷入的思维就是:所有step加起来的总和是n。俺这种思维去解决这个问题的话会显得很复杂。

  按动态规划的思维,要爬到第n阶,可以从第n-1阶爬1阶到达,也可以从第n-2阶爬2阶到达,因此爬到第n阶的方法有这么多种:

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

  按此思维的程序代码如下:

 1 class Solution {
 2 public:
 3     int climbStairs(int n) {
 4         if(n == 0 || n == 1 || n == 2)
 5             return n;
 6         
 7         int * dp = new int[n + 1];
 8         dp[0] = 0;
 9         dp[1] = 1;
10         dp[2] = 2;
11         
12         for(int i = 3; i < n + 1; i++)
13             dp[i] = dp[i - 1] + dp[i - 2];
14         
15         return dp[n];
16     }
17 };

 

posted @ 2015-06-09 17:07  峰子_仰望阳光  阅读(395)  评论(0编辑  收藏  举报