LeetCode(120) 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
题目
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

分析

本题类似于之前的一个障碍物的题目,用到动态规划的思想;

分析第i层的第k个顶点的最小路径长度表示为

f(i,k),则f(i,k)=minf(i1,k),f(i1,k1)+d(i,k); (注意每行的首尾边界需要特殊处理)

其中d(i,k)表示原来三角形数组里的第i行第k列的元素。

则可以求得从第一行到最终到第rows1行第k个元素的最小路径长度,最后再比较第rows1行中所有元素的路径长度大小,求得最小值。

题目要求:空间复杂度不要超过n。

AC代码

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if (triangle.empty())
            return 0;

        int rows = triangle.size();

        //动态规划,由于空间复杂度要求,现利用原始二维数组triangle改为存储当前(i,j)位置的最小和
        for (int i = 1; i < rows; ++i)
        {
            int cols = triangle[i].size();
            for (int j = 0; j < cols; ++j)
            {
                //本行的第一个元素
                if (0 == j)
                {
                    triangle[i][j] = triangle[i][j] + triangle[i - 1][j];
                }
                //本行的最后一个元素
                else if (j == cols - 1)
                {
                    triangle[i][j] += triangle[i - 1][j - 1];
                }
                else{
                    triangle[i][j] = min(triangle[i][j] + triangle[i][j - 1], triangle[i][j] + triangle[i - 1][j - 1]);
                }//else
            }//for
        }//for
        //最小路径和为最后一行的最小值
        int minSum = triangle[rows - 1][0];
        for (int j = 0; j < triangle[rows - 1].size(); ++j)
        {
            if (minSum > triangle[rows - 1][j])
                minSum = triangle[rows - 1][j];
        }//for
        return minSum;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214760.html