120. Triangle (1d)


brute force, DFS, over time limit
recursion n levels, like leetcode 22
choose element's left or right ...generate all possible solutions,
time: O(n^2)
https://leetcode-cn.com/problems/triangle/solution/di-gui-ji-yi-hua-dp-bi-xu-miao-dong-by-sweetiee/
DFS + memoization
time: O(n^2)
space: O(n^2)
DP - bottom up
i: level 層數 j: element
重複性: problem[i, j] = min( sub(i+1, j), sub(i+1, j+1)) + a[i, j]
state array: f[i, j]
DP 方程:f[i, j] = min( f(i+1, j), f(i+1, j+1)) + a[i, j]
from bottom to calculate !
time: O(n^2)
space: O(n)
這裡其實改成只用1d 就達成, 因為不用開到 2d 就可以把結果算出來 (可以參考上面連結)
follow up: use in-memory,
不開 dp[], 直接把
加到
Last updated
Was this helpful?