首页 > 代码库 > 【LeetCode】Climbing Stairs (2 solutions)

【LeetCode】Climbing Stairs (2 solutions)

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?

 

这是最简单的DP了,递推公式为f(n)=f(n-1)+f(n-2)

因此建立vector存放中间结果即可。

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

 

其实可以改进一下减少空间复杂度。

每个元素仅依赖于前两个元素,因此没有必要使用vector保存所有中间结果,只需要保存前两个。

class Solution {public:    int climbStairs(int n)     {        if(n <= 1)            return 1;        int pre1 = 1;    //n==0        int pre2 = 1;    //n==1        for(int i = 2; i <= n; i ++)        {            int cur = pre1+pre2;            pre1 = pre2;            pre2 = cur;        }        return pre2;    }};

 

【LeetCode】Climbing Stairs (2 solutions)