题目链接
https://leetcode.com/problems/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?
题目大意
爬楼梯,一次可以爬一步或者两步。如果要爬n层,问一共有多少种爬法。比如说,如果是3层,可以有[[1,1,1],[1,2],[2,1]]共3种方法。
解题思路
可以使用DP进行求解,是斐波那契数列的变形,arr[n] = arr[n-1] + arr[n-2] (n>2)
代码
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1 or n == 2:
return n
arr = [0 for i in range(n+1)]
arr[1] = 1
arr[2] = 2
for i in range(3,n+1):
arr[i] = arr[i-1]+arr[i-2]
return arr[n]