题目
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
1 | 输入:n = 2 |
示例 2:
1 | 输入:n = 7 |
提示:
0 <= n <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
最简单为递归实现,包含大量重复计算。
优化:记忆化递归,空间复杂度$O(N)$。
举例计算
- n=1, ans=1
- n=2, ans=2
- n=3, ans=3
- n=4, ans=5
可以看出实际上还是一个斐波那契数列。
代码
1 | class Solution { |