简繁EN

LeetCodeNo. 089

[LeetCode with Python] 70. Climbing Stairs

Contents

Problem

Problem page: https://leetcode.com/problems/climbing-stairs/
Topics: Dynamic Programming
Difficulty: Easy

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?


Analysis

If I use recursion to work backward from right to left, it's the same as doing a search, and I end up repeating parts of the search. Dynamic programming can usually take the place of search, so I use 1D dynamic programming here.
I use induction to work out f(x). If n=1, then f(1)=1. If n=2, I can take two steps of 1 stair each or one step of 2 stairs, so f(2)=2. If n=3, starting with 1 stair leaves f(2) ways to go, and starting with 2 stairs leaves f(1) ways. If n=4, starting with 1 stair leaves f(3) ways to go, and starting with 2 stairs leaves f(2) ways. This gives the formula f(x)=f(x-1)+f(x-2), which can be proved by mathematical induction.
Then you can see that since f(x) only depends on f(x-1) and f(x-2), you can reduce the space complexity to int[3]. And then you realize this is just a Fibonacci sequence problem.


Code

1
2
3
4
5
6
7
8
9
10
11
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
if n <= 1:
return 1
arr = [1, 1, 0]
for i in range(2, n + 1):
arr[2] = arr[0] + arr[1]
arr[0], arr[1] = arr[1], arr[2]
return arr[2]

Article link: https://xnerv.wang/en/leetcode-climbing-stairs/