Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
1) 原始的解法, DFS解法, 爆炸性复杂度2^n, 伪代码:
2) 此类方法的优化:
如果没解了,就不搜了(可行性剪枝) 不可行
如果解不可能最优,就不搜了(最优性剪枝) 可尝试
看看有没有重复计算, 伪代码如下:
复杂度O(n^2),n为所有的点的个数,求出了每个点到所有点的距离
3) 动态规划,思路:
记忆化搜索–动态规划最本质的思想:
Advantage: Easy to think and implement
Disadvantage: Expensive memory cost.
二维数组代码:
压缩空间:
当第i层状态,只跟i-1有关,就可压缩成一维的。把i-2以前的都扔掉
DP大类1:Two Sequence Dp 一般都可以压缩空间
DP大类2:sequence一般不可以,貌似本来就是一维的(后边具体分析).
2. Clues: 如何想到使用DP
Can not sort.
Find a maximum/minimum result
Decide whether something is possible or not
Count all possbile solutions: doesn’t care about the solution details, only the
count or possibility(若求所有的排列,只能全搜)