leetcode: 70. Climbing Stairs
来源:互联网 发布:星际淘宝网无弹窗 编辑:程序博客网 时间:2024/06/05 22:31
Q
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: 2Output: 2Explanation: There are two ways to climb to the top.1. 1 step + 1 step2. 2 steps
Example 2:
Input: 3Output: 3Explanation: There are three ways to climb to the top.1. 1 step + 1 step + 1 step2. 1 step + 2 steps3. 2 steps + 1 step
AC
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 a, b = 1, 2 for i in xrange(2, n): tmp = b b = a+b a = tmp return b# Time: O(n)# Space: O(1)class Solution2(object): """ :type n: int :rtype: int """ def climbStairs(self, n): prev, current = 0, 1 for i in xrange(n): prev, current = current, prev + current, return current# Time: O(2^n)# Space: O(n)class Solution3(object): """ :type n: int :rtype: int """ def climbStairs(self, n): if n == 1: return 1 if n == 2: return 2 return self.climbStairs(n - 1) + self.climbStairs(n - 2)if __name__ == "__main__": result = Solution().climbStairs(2) assert result == 2
阅读全文
0 0
- [LeetCode]70.Climbing Stairs
- LeetCode --- 70. Climbing Stairs
- [Leetcode] 70. Climbing Stairs
- [leetcode] 70.Climbing Stairs
- [leetCode]70. Climbing Stairs
- 70. Climbing Stairs LeetCode
- [LeetCode]70. Climbing Stairs
- 【LeetCode】70. Climbing Stairs
- leetcode 70. Climbing Stairs
- leetcode 70. Climbing Stairs
- LeetCode *** 70. Climbing Stairs
- 【LeetCode】70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- leetcode 70. Climbing Stairs
- [LeetCode]70. Climbing Stairs
- 【LeetCode】70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- #leetcode#70.Climbing Stairs
- httpclient使用cookie
- 03 实现一个Django的网站
- 返回值超过32位时的存储
- 四色原型
- eclipse安装JBoss Tools插件
- leetcode: 70. Climbing Stairs
- 浅析机器学习中的模型选择与调参(cross validation + grid search)
- 数据结构笔记(二)线性表的链式表示和基本操作
- ACM 字符串综合一
- C语言——Keywords&printf&scanf
- 欢迎使用CSDN-markdown编辑器
- C++两个原则
- IOS开发之——objectForKey与valueForKey在NSDictionary中的差异
- HDU