120. 三角形最小路径和

题目描述

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.

思路

自底向上的方法,这个方法好,最后可以直接得出结果。这里的辅助数组dp中的元素dp[i]的含义为当前层的第i个节点到最后一层的最小路径和。

代码实现

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {

    	int size = triangle.size();
    	if(size == 1)
    		return triangle[0][0];
    	vector<int> dp = triangle[size-1];//初始化
 
    	for(int row = size-1;row >=1;row--)
    	{
    		for(int i = 0;i<row;i++)
    		{   

                dp[i]=min(dp[i],dp[i+1])+triangle[row-1][i];
   	
    		}            
    	}
    	return dp[0];      
    }
};

posted on 2021-04-03 12:51  朴素贝叶斯  阅读(36)  评论(0编辑  收藏  举报

导航