[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
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】Climbing Stairs
- Leetcode算法学习日志-70 Climbing Stairs
- 【LeetCode】746. Min Cost Climbing Stairs
- leetcode 70:Climbing Stairs
- LeetCode_Climbing Stairs--爬楼梯
- leetcode 070 climbing stairs
- Leetcode 70 Climbing Stairs
- LeetCode-70-Climbing Stairs
- leetcode70-Climbing Stairs(斐波那契数列)
- leetcode - Climbing Stairs
- [LeetCode][Java] Climbing Stairs
- LeetCode -- Climbing Stairs
- [LeetCode] Climbing Stairs
- 65 leetcode - Climbing Stairs
- (java)leetcode-70:Climbing Stairs
- 【LeetCode 70】Climbing Stairs(Python)
- [LeetCode] Climbing Stairs
- 【LeetCode】70 - Climbing Stairs
- leetcode 070 —— Climbing Stairs
- LeetCode——Climbing Stairs