我有一个有两百行的三角形,需要找到从三角形顶部到底部的最大距离。
5
9 8
5 4 6
9 7 3 4
在这里,最短的距离将是5+8+4+3=20。最长的距离将是5+9+5+9=28。
我对要实现的算法有一个很好的想法,但我正在努力将其转化为代码。
我的计划是:从倒数第二行开始,添加自底部行可能路径的最大值,并向上迭代。
例如,上述三角形将变为:
28
23 19
14 11 10
9 7 3 4
这比暴力破解要高效得多,但我有两个普遍的问题:
Using brute-force, how do I list all the possible paths from top to bottom (can only move to adjacent points)? I tried using this (triangle is the list of lists containing the triangle):
points=list(itertools.product(*triangle))
but this contains all possible combinations from each row, not just adjacent members. Project Euler #18 - how to brute force all possible paths in tree-like structure using Python? This somewhat explains a possible approach, but I'd like to use itertools and any other modules (as pythonic as possible)
How would I go about iterating the strategy of adding each maximum from the previous row and iterating to the top? I know I have to implement a nested loop:
for x in triangle: for i in x: i+=? #<-Not sure if this would even increment it edit: what I was thinking was: triangle[y][x] = max([triangle[y+1][x],triangle[y+1][x+1]])