Two methods: one is tricky the other use rolling array. Both O(n) space
    In this case better go from bot to top

    1. Rolling array: using inf

      1. class Solution:
      2. def minimumTotal(self, triangle: List[List[int]]) -> int:
      3. n = len(triangle)
      4. result = [[float("inf")] * n for _ in range(2)]
      5. result[0][0] = triangle[0][0]
      6. for i in range(1,n):
      7. for j in range(i):
      8. result[i % 2][j] = min(result[(i-1) % 2][j-1], result[(i-1) % 2][j]) + triangle[i][j]
      9. print(j)
      10. print(result)
      11. return min(result[(n-1) % 2])
    2. One array

      1. class Solution:
      2. def minimumTotal(self, triangle: List[List[int]]) -> int:
      3. n = len(triangle)
      4. result = [0] * n
      5. result[0] = triangle[0][0]
      6. for i in range(1,n):
      7. for j in range(i, -1, -1):
      8. if j == 0:
      9. result[j] = result[j] + triangle[i][j]
      10. elif j == i:
      11. result[j] = result[j-1] + triangle[i][j]
      12. else:
      13. result[j] = min(result[j-1], result[j]) + triangle[i][j]
      14. return min(result)