题目链接:https://leetcode.com/problems/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).
思路:本题是动态规划的题目。题意是说从上一个位置 pos[i][j],可以向下走到pos[i+1][j] 或者 pos[i+1][j+1];
如果从上向下扫描,则很难写出状态转移方程,从下往上扫描就会很容看出dp[i][i] = max(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j];
最后一行的状态就是由其本身的值决定的,因此在初始化dp数组的时候就赋值为其本身。另外由于一个位置的值dp[i][j]在被dp[i-1][j] 使用之后将不会再被使用,因此可以优化dp数组成一维,即最大一行triangle[triangle.size()-1].size的大小。时间复杂复为O(N), 空间复杂度为O(N).
代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size() ==0) return 0;
int len = triangle.size();
vector<int> dp(triangle[len-1].size());
for(int i = 0; i < dp.size(); i++)
dp[i] = triangle[len-1][i];
for(int i = len-2; i >=0; i--)
for(int j =0 ; j < triangle[i].size(); j++)
dp[j] = min(dp[j], dp[j+1]) + triangle[i][j];
return dp[0];
}
};