动态规划系列 Leetcode 70. 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?

Note: Given n will be a positive integer.

 

Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

 

Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

这个一道基本动态规划题目,做动态规划题目有四个步骤:
1)确定原问题和子问题
2)确定状态
3)确认边界状态的值
4)确定状态转移方程
 1 #include <stdio.h>
 2 
 3 #include <vector>
 4 class Solution {
 5 public:
 6     int climbStairs(int n) {
 7         std::vector<int> dp(n + 3, 0);
 8         dp[1] = 1;
 9         dp[2] = 2;
10         for (int i = 3; i <= n; i++){
11             dp[i] = dp[i-1] + dp[i-2];
12         }
13         return dp[n];
14     }
15 };
16 
17 int main(){
18     Solution solve;
19     printf("%d\n", solve.climbStairs(3));    
20     return 0;
21 }

 

posted @ 2018-04-07 16:27  Hwangzhiyoung  阅读(165)  评论(0编辑  收藏  举报