程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Sword finger offer python:43 Maximum / minimum value of gift

編輯:Python

subject : In a m*n There is a gift in every space of the chessboard , Every gift has a certain value ( Value greater than
0). You can learn from the top left corner Start taking the gifts in the box , And move right or down one space at a time 、 Until you get to the end of the board The lower right corner . Given the value of a chessboard and its gifts , Please count your maximum / How much less valuable gifts can you get ?

Ideas : Dynamic programming .

Backward analysis , There is one i*j Matrix , The last step , Want to get to (i,j), Or from (i-1,j), Or from (i , j-1). The problems encountered at each step are the same , It's just a different way , Get different values .

f(i,j)=max(f(i,j-1)+f(i-1,j))+g(i,j) g(i,j) Indicates that the coordinates are (i,j) The value of gifts in the box

Recursive solution , There will be a lot of double counting , Through recursive analysis , Use a bottom-up loop to solve ( This topic is analyzed backwards , Direct solution )

The push process is as follows :

Intermediate results can be directly saved to the original array .

for loop , Next line per loop / Column , Calculate the sum of each position , Maximum / Minimum value use max/min Judge .

Code :

class Solution:
def func(self , array):
if len(array) <= 0 or array is None:
return 0
rows = len(array)
cols = len(array[0])
for i in range(rows):
for j in range(cols):
if i == 0 and j == 0:
continue
if i == 0:
array[i][j] += array[i][j -1]
elif j == 0:
array[i][j] += array[i -1][j]
else:
array[i][j] += max(array[i -1][j] , array[i][j-1]) # The greatest value , Minimum replacement min that will do
return array[rows-1][cols-1]
a = [[1,10,3,8] , [12,2,9,6] , [5,7,4,11] , [3,7,16,5]]
s = Solution()
print(s.func(a))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved