LeetCode_C++Climbing_Stairs动态规划Beats100%的爬楼梯问题

题目:

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
----------------------------------------------------------------------------------------------------------------------------------

爬楼梯问题是运用动态规划思想解决的典型问题之一。

简单来说:动态规划就是依赖于当前状态,随即引起状态的转移。

不同于分而治之的分治法,动态规划(以下用DP来代替)分解过后的子问题往往不是相互之间独立的。

动态规划问题一般包含三个要素:

    1.起始状态

    2.终止状态

    3.状态转移方程

在爬楼梯问题中:

如果只有一节台阶,显然只有从0->1一种方法,就是f(1)=1; 

如果有两节台阶,那么有0->1->2/0->2两种方法,f(2)=2;

 我们先假设爬n级阶梯一共有f(n)种方法,那么当我们爬到第n级台阶之前,只有两种情况,要么在第n - 1级台阶,要么在第n - 2级台阶上。

由此可以分析出:f(n) = f(n - 1)+f(n-2)<=>DP中的状态转移方程

所以在了解以上分析之后,不难写出以下代码:

class Solution {
public:
    int climbStairs(int n) {
        vector <int> step (n);
        step[0] = 1;
        step[1] = 2;
        if( n == 2 )
        {
            return step[n-1];
        }
        else
        {
            for( int i=2;i<n;i++ )
            {
                step[i] = step[i-1] + step[i-2];
            }
            return step[n-1];
        }
        
    }
};

作为人生中第一个Beats 100%还是有点小激动的


当然其他思路解题也是可以的,只是没有DP这样简单快捷,再此就不在赘述了。

猜你喜欢

转载自blog.csdn.net/qq_35180757/article/details/81013439
今日推荐