Project Euler problem 67: find maximum cost path in 100-row triangle

前端 未结 5 1163
长情又很酷
长情又很酷 2021-02-11 06:27

In Project Euler\'s problem 67 there is a triangle given and it contains 100 rows. For e.g.

        5
      9  6
    4   6  8
  0   7  1   5

I.e. 5 + 9 + 6 + 7          


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-11 07:19

    To build off of @Matt Wilson's answer, using a two-dimensional array to hold the numbers would be a fairly simple solution. In your case, you would encode the triangle

          5
        9  6
      4   6  8
    0   7  1   5
    

    as the array

    [5][ ][ ][ ]
    [9][6][ ][ ]
    [4][6][8][ ]
    [0][7][1][5]
    

    From here, a node at position (i, j) has children at (i + 1, j) and (i + 1, j + 1) and parents at position (i - 1, j) and (i - 1, j - 1), assuming those indices are valid.

    The advantage of this approach is that if your triangle has height N, the space required for this approach is N2, which is just less than twice the N(N + 1) / 2 space required to actually store the elements. A linked structure like an explicit graph would certainly use more memory than that.

提交回复
热议问题