Euler project #18 approach

后端 未结 9 892
鱼传尺愫
鱼传尺愫 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:01

    Actually, you needn't start bottom-up; you may as well start top-down, providing you do it properly.

    The way it works bottom up is best illustrated by the taking what happes at each level of the pyramid. The path surely must cross each level at some point.

        x
       x x
      x h x
     x y y x
    x y y y x
    

    Let's say it's h. From the definition of allowable paths, the path can only follow down into the y-marked places, which forms a problem similar to the original - if we find a maximal path through the ys and the maximal path of the whole triangle actually goes through h, it will surely follow along a maximal path in ys (if not, you can switch the part of path in the smaller triangle and get an overall better path).

    So if you structure your algorithm top-down computing the maximal path from the current node down, you get the correct result (ie. maximal path value, from which you can easily get the path itself).

    Now, this takes O(N) (N meaning the number of the numbers), because for each place, you just consider two paths and use the pre-computed values from the lower level.

    Virtually the same algorithm can be implemented top down, where you start at the top and recurse down, provided you memoize the result.

    best_length(node)
    { 
      if(node is terminal)
        return value(node)
      int m = 0
      for(next : lower neighbors of node)
        m = max(best_length(next), m)
      return m + value(node);
    }
    

    Another possibility of doing this top-down would be just reverse the computation. You start at the top, for each node considering its upper neighbors, and get the path length from the top ending in this node (instead of the path going from this node down to the bottom row). At the end, you gather the data from the bottom row and you're done.

提交回复
热议问题