题目链接
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 step + 1 step
- 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
python3代码实现:
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] + [1] + [2] + [0] * (n - 2)
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
代码实现思路:
n<=1,此时只有一种。
n>1时,对于每一个台阶i,要到达台阶,最后一步都有两种方法,从i-1迈一步,或从i-2迈两步。
也就是说到达台阶i的方法数=达台阶i-1的方法数+达台阶i-2的方法数。所以该问题是个DP问题。
d(0) = 1
d(1) = 1
d(2) = d(2-1) + d(2-2)
d(3) = d(3-1) + d(3-2)
……
好吧,状态转移方程其实就是Fibonacci数列。
python3 递归实现:
这种方法在LeetCode的运行环境下是不通过的,因为递归的栈太深。
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
if n == 2:
return 2
if n > 1:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
s = Solution()
res = s.climbStairs(4)
print(res)