- 描述
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,不能向后移动。换句话说,即可以不移动索引或者索引+1。 - 思路
可以考虑逆推的方式进行求解。看例子中的最后两行,倒数第二行中,6可以跟4或1进行组合,5可以跟1或8进行组合,7可以跟8或3组合,而这种组合可以确定只能跟可以选择的最小数字进行组合,即6只能跟1进行组合,5只能跟1进行组合,7只能跟3进行组合, 将组合后的数字重新赋值给倒数第二行 ,这样,即可删除最后一行,继续向前遍历。可以重复的进行“删行”,直到该行只有1个元素,就得到了最终的结果。由于每次的元素都保存在原集合中,故空间复杂度为常量C,符合题意。 - 代码(c#)
public int MinimumTotal(IList<IList<int>> triangle)
{
for (int i = triangle.Count-2; i>-1 ; i--)
{
for (int j = 0; j < triangle[i].Count; j++)
{
triangle[i][j] += Math.Min(triangle[i+1][j], triangle[i+1][j+1]);//选出最小的可组合项
}
}
return triangle[0][0];
}
- 总结
在算法题对空间复杂度有要求时,可以考虑将题目给定的集合进行存储数据。 - 相关链接
LeetCode原题:https://leetcode.com/problems/triangle/description/