Here is what I learned 动态规划
notes when, but also a common problem. Benpian hope that through a few questions to help you better understand the dynamic programming
Problem : a 10 level, you can only take one step or two steps, went to the top of several moves?
If only the last step, then there are two cases, the final step 8->10
or 9->10
-go one or two steps, if 0 -> 8
there is a method in X, 0 -> 9
Y-ways, you can think F(10) = F(9) + F(8)
, and so on, come formula F(n) = F(n-1) + F(n-2)
, n = 1 or until n = 2F(1) = 1, F(2) = 2
Important concept of dynamic programming
1. The optimal substructure
F(10) = F(9) + F(8)
2. border
F(1) = 1, F(2) = 2
3. The state transition formula
F(n) = F(n-1) + F(n-2)
It can be summarized in the following formula
F(1) = 1;
F(2) = 2;
F(n) = F(n-1)+F(n-2)(n>=3)
Code
- Recursion
def climbs(n):
if n < 1:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
return climbs(n-1) + climbs(n-2)
print(climbs(10))
"""
89
"""
The above method will construct a binary tree, the height is N, but requires repeated many computing nodes , so the time complexity is the number of nodes, is approximately equal to O (2 ^ n)
- Using cache mode
cache = {1:1, 2:2}
def fibs(n):
if n not in cache:
cache[n] = fibs(n-1) + fibs(n-2)
return cache[n]
print fibs(10)
"""
89
"""
Calculating only the use of cache in the form of approximately N times, the time complexity is O (n) , a cache to store all of the results form, will be relatively much space complexity O (n)
- Bottom-up method
def fibs(n):
if n < 1:
return 0
if n == 1:
return 1
if n == 2:
return 2
a, b = 1, 2
count = 3
while count <= n:
res = a + b
a, b = b, res
count += 1
return b
print fibs(10)
"""
89
"""
To ensure that the above time complexity is O (n-) , while reducing the space complexity is O (1)
Abnormal level problem
If one can on one level, can the two, but also on the n, there are several moves?
Suppose there are five steps, then f(5) = f(4)+f(3)+f(2)+f(1)+f(0)
, the last step corresponding to sequentially jump 1, 2, .., 5 steps.
Likewise, wherein f(4) = f(3)+f(2)+f(1)+f(0)
, into the above equation can be obtained f(5)=2*f(4)
. Therefore stars
- State transition equation:
f(n) = 2 * f(n-1)
Border: f (1) = 1, f (2) = 2
def fibs(n): if n < 2: return n return 2 * fibs(n-1) print(fibs(3)) # 4
understanding
If a better understanding of dynamic programming, a deep impression is
2 = 1 + 1
3 = 2 + 1 而不是 3 = 1 + 1 + 1
It is based on the idea of space for time