动态规划系列 Leetcode 70. Climbing Stairs

Posted Hwangzhiyoung

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划系列 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 }

 

以上是关于动态规划系列 Leetcode 70. Climbing Stairs的主要内容,如果未能解决你的问题,请参考以下文章

动态规划_leetcode70

经典动态规划——从LeetCode题海中总结常见套路

LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)

#动态规划 LeetCode 70 爬楼梯

「动态规划」LeetCode 70(爬楼梯)

Leetcode刷题100天—70. 爬楼梯(动态规划)—day76