Euler project #18 approach

后端 未结 9 876
鱼传尺愫
鱼传尺愫 2020-11-30 22:23

I am looking into an Euler project. Specifically #18.
To sum up, the idea is to find the max path from a triangle:

   3
  7 4
 2 4 6  
8 5 9 3
<         


        
9条回答
  •  隐瞒了意图╮
    2020-11-30 23:13

    Using your example, the "bottom up" way to approach it is:

    Examining the bottom row, the most you can get from each element is

    8,5,9,3

    Examining the next-to-bottom row, the most you can get from each element is (depending on whether you go left or right from it):

    2+max(8,5),4+max(5,9),6+max(9,3) = 10,13,15

    So this is great; we've eliminated 2 rows by squishing them together to replace them with one row, reducing the problem to

         3
       7   4
    10  13  15
    

    Obviously we can just keep repeating this. Examining the next row up, the most you can get from each element is

    7+max(10,13),4+max(13,15) = 20,19

    And so from the top, the most you can get is

    3+max(20,19) = 23

    QED.

提交回复
热议问题