1

来源:互联网 发布:拼团平台源码 编辑:程序博客网 时间:2024/05/16 01:30

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.

思路:假设距离走到第n阶台阶只差一步,则可能是走到了n-1阶或者n-2阶。n-1阶到第n阶dp[n-2],以及n-2阶到第n阶有dp[n-3]种情况。且n-1阶到第n阶,n-2阶到第n阶,完全独立。dp[n-1]=dp[n-2]+dp[n-3]。

class Solution {public:    int climbStairs(int n) {        vector<int> dp(n);//给容器开辟空间dp[0]=1;dp[1]=2;for(int i=2;i<n;i++){dp[i]=dp[i-1]+dp[i-2];}return dp[n-1];    }};