题目:
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
代码:
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { if (triangle.size()<1) return 0; int min_sum = triangle[0][0]; for ( int i = 1; i<triangle.size(); ++i ) { for (int j = 0; j<triangle[i].size(); ++j ) { if (j==triangle[i].size()-1) { triangle[i][j] += triangle[i-1][j-1]; min_sum = std::min(min_sum, triangle[i][j]); } else if ( j==0 ) { triangle[i][0] += triangle[i-1][0]; min_sum = triangle[i][j]; } else { triangle[i][j] += std::min(triangle[i-1][j-1], triangle[i-1][j]); min_sum = std::min(min_sum, triangle[i][j]); } } } return min_sum; } };
tips:
这种做法时间复杂度O(n),空间复杂度O(1)。
思路很简单,就是遍历每层元素的同时,把这一个元素的值更新为走到该位置的最小路径和。
min_sum这个遍历记录当前最小值,其实只有当遍历到最后一层的时候才有用,偷懒就没有改动了。
但是有个缺点就是把原来的triangle的结构都破坏了,研究一下用O(n)额外空间,但不破坏原有triangle的做法。
时间: 2024-10-04 00:51:14