您的位置:首页 > 大数据 > 人工智能

[Leetcode]Climbing Stairs

2015-01-16 23:12 288 查看
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?

每次可以走1个或两个台阶,求走n个台阶有多少种走法~用递归或者动态规划都可以~代码如下~

class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
if n <= 0: return 0
dp = [0, 1, 2]
for i in xrange(3, n + 1):
dp.append(dp[i - 1] + dp[i - 2])
return dp


很明显,这题的递推公式是f(n) = f(n - 1) + f(n - 2), 正好是斐波拉切数列的定义~用递归的解法时间复杂度为O(n),但斐波那契数列还有一种O(logn)的解法,具体参考参考自http://blog.csdn.net/linhuanmars/article/details/23976963
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python