美文网首页
Leetcode 120. Triangle

Leetcode 120. Triangle

作者: persistent100 | 来源:发表于2017-09-05 11:03 被阅读0次

    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.

    分析

    找出一个三角形从顶到底最短路径。很简单的动态规划问题,从上到下,依次计算到当前行左边路线和右边路线哪个是最短距离。不过需要两端的点只有一条路,需要另处理。
    当然也可以从下到上,更方面了。

    int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSizes) {
        int ans=0;
        for(int i=1;i<triangleRowSize;i++)
        {
            triangle[i][0]=triangle[i-1][0]+triangle[i][0];
            for(int j=1;j<triangleColSizes[i]-1;j++)
            {
                int left=triangle[i-1][j-1]+triangle[i][j];
                int right=triangle[i-1][j]+triangle[i][j];
                if(left<right)
                    triangle[i][j]=left;
                else
                    triangle[i][j]=right;
            }
            triangle[i][ triangleColSizes[i]-1 ]=triangle[i-1][ triangleColSizes[i]-2 ]+triangle[i][ triangleColSizes[i]-1 ];
        }
        ans=triangle[triangleRowSize-1][0];
        for(int j=1;j<triangleColSizes[triangleRowSize-1];j++)
            if(triangle[triangleRowSize-1][j]<ans)
                ans=triangle[triangleRowSize-1][j];
        
        return ans;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 120. Triangle

          本文链接:https://www.haomeiwen.com/subject/zfrujxtx.html