题目描述:
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).
解题思路:
因为这道题对数字的路径是有约束的,从上方往下寻找最小值只能找到一时的最小值,也就成了贪心算法,若真要从最顶开始寻找,只能用递归把所有可能性都找一遍,但那样太耗费空间了,n阶三角形就要用到2n次函数。
因此这题最好是从最低端开始寻找,往上层遍历。
代码:
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int>>& triangle) { 4 int n = triangle.size(); 5 vector<int> sum (triangle[n-1]); //记录下一层到最后一层的路径最小值 6 for(int i = n-2; i >= 0; i--){ 7 for(int j = 0; j < triangle[i].size(); j++){ 8 sum[j] = triangle[i][j] + min(sum[j], sum[j+1]); //更新每一层到最后一层的路径最小值 9 } 10 } 11 return sum[0]; //最后的路径最小值一定在sum[0]处 12 } 13 };