您的位置:首页 > 编程语言 > Python开发

[Leetcode]@python 70. Climbing Stairs

2016-01-13 10:34 281 查看

题目链接

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
= 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: