Dynamic programming component one: Determine the status
[Status] It
belongs to Dinghai Shenzhen in dynamic programming.
Generally speaking, when solving dynamic programming, you need to open an array f. What does each element f[i] and f[i][j] of the array mean, similar to math problems What do X, Y and Z stand for
[Determining the state] Two consciousnesses are needed
-the last step
-sub-problems. For
example, in this question:
[Key Points]
1. We don’t care what the previous ak-1 and k-1 are, but we can be sure that the previous The coin combination must be 27-ak
2. The number of 27-ak must be the least
So-------------------->
1. We ask to spell out 27-ak with the least number of coins.
2. It is worth mentioning that the original problem is spelled out 27.
3. We transformed the original problem into a sub-problem, and the scale is smaller: 27-ak
4 , In order to simplify the definition, we set the state f(X) = how many coins are used to make X at least, so the original problem is to find f(27), now we find f(27-ak)
The above is [the part that determines the status]
Now, we don’t know the face value of the coin at the last step. Is it 2 or 5 or 7?
Here is the recursive solution:
class Solution:
'''
面值2 5 7
'''
def pay(self, sum):
res = float('inf')
if sum == 0:
return 0
if sum >= 2:
res = min(res,self.pay(sum-2)+1)
if sum >= 5:
res = min(res,self.pay(sum-5)+1)
if sum >= 7:
res = min(res,self.pay(sum-7)+1)
return res
a = Solution()
print(a.pay(27))
However, there will be repeated recursion:
how to avoid it?
To save the calculation results -> please see dynamic programming component two
Dynamic programming component two: transfer equation
Let the equation of state f(X) = how many coins should be used to make X at least
Dynamic programming component three: initial test conditions and boundary conditions
Dynamic programming component four: calculation sequence
solution:
class Solution:
'''
面值1 2 5 7
'''
def pay(self, sum):
values = [1, 2, 5, 7]
memory = [float('inf')] * (sum+1)
memory[1], memory[2], memory[5], memory[7]= 1, 1, 1, 1
for i in range(3,sum+1):
if i not in values:
memory[i] = min(memory[i], memory[i-1]+1, memory[i-2]+1, memory[i-5]+1, memory[i-7]+1)
return memory[sum]
a = Solution()
print(a.pay(271))
The second question: The
solution is as follows:
class Solution:
def calculate(self,m,n):
map = [[0] * n for i in range(m)]
map[0][0] = 1
'''
目的地是:
map[m-1][n-1]
'''
for i in range(1, n):
map[0][i] = map[0][i-1]
for i in range(1, m):
map[i][0] = map[i-1][0]
for i in range(1,m):
for j in range(1,n):
map[i][j] = map[i-1][j] + map[i][j-1]
return map[i][j]
sol = Solution()
print(sol.calculate(10,10))