Leetcode70爬楼梯
爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/climbing-stairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution 1
(n) = (n-1) + (n-2)
class Solution:
def climbStairs(self, n: int) -> int:
if type(n) is not int:
raise Exception("type(n) is not int")
if n < 0:
raise Exception("n < 0")
a = 0
b = 0
c = 1
for _ in range(n):
a = b
b = c
c = a + b
return c
Solution 2
通项公式(斐波那契)
import math
class Solution:
def climbStairs(self, n: int) -> int:
if type(n) is not int:
raise Exception("type(n) is not int")
if n < 0:
raise Exception("n < 0")
sqrt5 = math.sqrt(5)
fibn = math.pow((1 + sqrt5) / 2, n + 1) - \
math.pow((1 - sqrt5) / 2, n + 1)
return (int)(fibn / sqrt5)