[LeetCode]|[LeetCode] 070. Climbing Stairs
070. 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?
Note: Given n will be a positive integer.
Example:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
【[LeetCode]|[LeetCode] 070. Climbing Stairs】Solution:
class Solution1:
"""
递归做法
"""
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
if n == 2:
return 2
return self.climbStairs(n-1) + self.climbStairs(n-2)class Solution2:
"""
非递归做法
"""
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
pre_1_step = 1
pre_2_step = 0
count = 1
for i in range(1, n+1):
count = pre_1_step + pre_2_step
pre_2_step = pre_1_step
pre_1_step = count
return countclass Solution:
"""
非递归做法,比上一个方法快
"""
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
F = [0, 1]
count = 1
for i in range(n):
count = F[0] + F[1]
F[0] = F[1]
F[1] = count
return count
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- LeetCode|LeetCode 876. 链表的中间结点