LeetCode face questions 10- II. Frog jump steps to prove safety issues [Offer] [Easy] [] [Dynamic Programming Python]
problem
A frog can jump on a Class 1 level, you can also hop on level 2 level. The frog jumped seeking a total of n grade level how many jumps.
Answer needed modulo 1e9 + 7 (1000000007), the initial result is calculated as: 1000000008, return to 1.
Example 1:
输入:n = 2
输出:2
Example 2:
输入:n = 7
输出:21
prompt:
0 <= n <= 100
NOTE: The main problem with the station 70 issues the same.
Thinking
Dynamic Programming
初始条件和斐波那契数列有点区别:dp_0 = 1,dp_1 = 1。
fib(n) = fib(n - 1) + fib(n - 2)
注意,fib(n)会越界,所以最好是:
fib(n) % 1000000007 = (fib(n - 1) % 1000000007 + fib(n - 2) % 1000000007) % 1000000007
但是因为 Python 中整形数字的大小限制取决计算机的内存(可理解为无限大),因此可不考虑大数越界问题。
Time complexity: O (n-)
Complexity Space: O (. 1)
Python3 Code
class Solution:
def numWays(self, n: int) -> int:
# 初始条件和斐波那契数列有区别
dp_0, dp_1 = 1, 1
for _ in range(n):
dp_0, dp_1 = dp_1, dp_0 + dp_1
return dp_0 % 1000000007