Try   HackMD

70. Climbing Stairs


My Solution

Solution 1: Brute Force (TLE)

The Key Idea for Solving This Coding Question

C++ Code

class Solution { public: int climbStairs(int n) { if (n <= 2) { return n; } return climbStairs(n - 1) + climbStairs(n - 2); } };

Time Complexity

O(2n)

Space Complexity

O(2n)

Solution 2: Top-down DP

The Key Idea for Solving This Coding Question

C++ Code

class Solution { public: int climbStairs(int n) { vector<int> stepToCnt(n + 1, -1); stepToCnt[1] = 1; if (n == 1) { return stepToCnt[1]; } stepToCnt[2] = 2; if (n == 2) { return stepToCnt[2]; } return dp(n, stepToCnt); } private: // dp returns the number of ways for climbing to the n-th step. int dp(int n, vector<int> &stepToCnt) { if (stepToCnt[n] > 0) { // We have calculated stepToCnt[n]. // Just reuse its answer. return stepToCnt[n]; } stepToCnt[n] = dp(n - 1, stepToCnt) + dp(n - 2, stepToCnt); return stepToCnt[n]; } };

Time Complexity

O(n)

Space Complexity

O(2n)=O(n)

Solution 3: Buttom-up DP

The Key Idea for Solving This Coding Question

C++ Code

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

Time Complexity

O(n)

Space Complexity

O(n)

Solution 4: Buttom-up DP

The Key Idea for Solving This Coding Question

C++ Code

class Solution { public: int climbStairs(int n) { int a = 1; if (n == 1) { return a; } int b = 2; if (n == 2) { return b; } int c; for (int i = 3; i <= n; ++i) { c = a + b; a = b; b = c; } return c; } };

Time Complexity

O(n)

Space Complexity

O(1)

Miscellaneous