menu

[LeetCode] 070. Climbing Stairs

Problem (Easy)

070. Climbing Stairs

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

Approach 1: (My Solution - Backtracking [Time Limit Exceeded!])

Idea

Use Backtracking algorithm to find all possible ways.

Solution

class Solution1:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = [0]
        self.backtrack(res, n, 0)
        return res[0]

    def backtrack(self, res, n, step):
        if step > n:
            return
        if step == n:
            res[0] += 1
            return
        for i in [1,2]:
            self.backtrack(res, n, step+i)

Complexity

  • Time: $O()$
  • Space: $O()$

Approach 2: (My Solution - Dynamic Programming)

Idea

  • State update rule: (1-D dp state matrix) dp[i] = dp[i-1] + dp[i-2];
  • Initial state: dp[0] = 1, dp[1] = 2. if n == 1, return 1.

Solution

python
class Solution1:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        dp = [0 for _ in range(n)]
        dp[0], dp[1] = 1, 2
        for i in range(2, n):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[-1]

Complexity

  • Time: $O()$
  • Space: $O()$

Approach 2: (My Solution - Dynamic Programming)

Idea

  • State update rule: (1-D dp state matrix) dp[i] = dp[i-1] + dp[i-2];
  • Initial state: dp[0] = 1, dp[1] = 2. if n == 1, return 1.

Solution

python
class Solution2:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        dp = [0 for _ in range(n)]
        dp[0], dp[1] = 1, 2
        for i in range(2, n):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[-1]

Complexity

  • Time: $O()$
  • Space: $O()$

Approach 3: (Fibonacci - Improved)

Idea

  • This problem is actually a Fibonacci series.
  • Improve the Fibonacci generating method.

Solution

python
class Solution3:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        a, b = 1, 2
        for _ in range(2, n):
            c = a + b
            a, b = b, c
        return b

Complexity

  • Time: $O()$
  • Space: $O()$



KF

Comments