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.
想法是这样的 可以把triangle看作是一个tree 从上到下 对于每一个点来说 他的前一步只能是左上或右上
也就是说 他只能把其中的一个自己身上 加哪个呢 取小的那个
比如对于上面的输入
对于3来说 只能选2
5的上方左右分别是3,4 选择小的3 ….
到最后 取最底层中最小的就可以了
代码如下
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle.size() == 0) return 0;
List<Integer> pre = triangle.get(0);
for (int i=1; i<triangle.size(); i++) {
List<Integer> list = triangle.get(i);
int sum = list.get(0) + pre.get(0);
list.set(0, sum);
sum = list.get(list.size()-1) + pre.get(pre.size()-1);
list.set(list.size()-1, sum);
for (int j=1; j<list.size()-1; j++) {
sum = list.get(j) + Math.min(pre.get(j-1), pre.get(j));
list.set(j, sum);
}
pre = list;
}
int min = Integer.MAX_VALUE;
for (int n : pre) {
min = min < n ? min : n;
}
return min;
}
后来才发现 在这过程中修改了输入 相当于使用了O(n)得空间 n表示triangle中的数字个数 大于行数
可以优化一下 因为每次只用到上一行的计算结果 所以可以用一个O(n)的数组存就可以了
下面的思路有点特别 是从下到上 同时避免了边界检查 看起来简洁很多
int minimumTotal(vector<vector<int> > &triangle) {
int n = triangle.size();
vector<int> minlen(triangle.back());
for (int layer = n-2; layer >= 0; layer--) // 从下到上 逐层遍历
{
for (int i = 0; i <= layer; i++) // Check its every 'node'
{
// Find the lesser of its two children, and sum the current value in the triangle with it.
minlen[i] = min(minlen[i], minlen[i+1]) + triangle[layer][i];
}
}
return minlen[0];
}