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变量原处修改值就可以甚至只用O(1)的额外空间,我真机智。
java方法见code2
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
height = len(triangle)
for i in range(1,height):
cur = triangle[i]
cur[0] = cur[0] + triangle[i-1][0]
for t in range(i-1):
cur[t+1] = cur[t+1] + min(triangle[i-1][t],triangle[i-1][t+1])
cur[-1] = cur[-1] + triangle[i-1][-1]
# print(triangle)
return min(triangle[-1])
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
// 默认初始化为0
int[] A = new int[triangle.size()+1];
for(int i=triangle.size()-1;i>=0;i--)
for(int j=0;j<triangle.get(i).size();j++)
{
A[j] = Math.min(A[j],A[j+1]) + triangle.get(i).get(j);
}
return A[0];
}
}
// 3.20 我怎么写了个自顶向下的呢哈哈哈哈哈傻的
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int len = triangle.size();
if(len==0)
return 0;
int[] res = new int[len];
res[0] = triangle.get(0).get(0);
for(int i=1;i<len;i++)
{
for(int j=i;j>=0;j--)
{
if(j==0)
res[j] += triangle.get(i).get(j);
else if(j==i)
res[j] = triangle.get(i).get(j) + res[i-1];
else
res[j] = Math.min(res[j],res[j-1])+triangle.get(i).get(j);
}
}
int min = Integer.MAX_VALUE;
for(int num : res)
min = Math.min(min,num);
return min;
}
}