12
08/2015
[LeetCode] Triangle
Triangle
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.
解题思路:
动态规划。用d来记录从根到页的最短路径,i为当前行数。则有
d[j] = d[j-1] + triangle[i][j],j==i时
d[j] = d[0] + triangle[i][0], j==0时
d[j] = min(d[j-1], d[j]) + triangle[i][j],其他。
注意计算d[j]时,会用到上一次的d[j-1],因此可以按d[i..0]的顺序来计算。
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); if(n==0){ return 0; } if(n==1){ return triangle[0][0]; } int d[n]; d[0] = triangle[0][0]; for(int i=1; i<n; i++){ for(int j=i; j>=0; j--){ //这里从由高到低 if(j==i){ d[j] = d[j-1] + triangle[i][j]; }else if(j==0){ d[j] = d[0] + triangle[i][0]; }else{ d[j] = min(d[j-1], d[j]) + triangle[i][j]; } } } int minPath = d[0]; for(int i=1; i<n; i++){ minPath = min(d[i], minPath); } return minPath; } };
转载请注明:康瑞部落 » [LeetCode] Triangle
0 条评论