美文网首页
120. Triangle

120. Triangle

作者: juexin | 来源:发表于2017-01-09 17:06 被阅读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.

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        if(n==1)
          return triangle.get(n-1).get(n-1);
        int[][] f = new int[n][n];
        for(int i=0;i<n;i++)
          for(int j=0;j<n;j++)
          {
              f[i][j] = 0;
          }
          
        for(int j=0;j<n;j++)
          f[n-1][j] = triangle.get(n-1).get(j);   // 需要把数组最后一行的值赋给f[n-1][j]
        
        for(int i=n-2;i>=0;i--)
          for(int j=0;j<=i;j++)
          {
              f[i][j] = Math.min(f[i+1][j],f[i+1][j+1]) + triangle.get(i).get(j);   // f(i,j) = min{f(i+1,j),f(i+1,j+1)} + triangle(i,j);
          }
        return f[0][0];
        
    }
}

相关文章

  • Leetcode-120Triangle

    120. Triangle Given a triangle, find the minimum path sum...

  • LeetCode 120. Triangle

    10-16 LeetCode 120. Triangle Triangle Description Given a...

  • Triangle

    //120. TriangleGiven a triangle, find the minimum path su...

  • 120. Triangle

    top to down的方案状态转移: f(x,y) = min(f(x-1, y-1), f(x-1, y)) ...

  • 120. Triangle

    Given a triangle, find the minimum path sum from top to b...

  • 120. Triangle

    https://leetcode.com/problems/triangle/description/解题思路:d...

  • 120. Triangle

    题目 思路 动态规划的题目。 递归 二维数组保存dp[i][j]:到(i,j)位置时的最小值 自底向上一维数组 ...

  • 120. Triangle

    题目 Given a triangle, find the minimum path sum from top t...

  • 120. Triangle

    从底部往上算,递归公式: dp(i,j) 表示从tri[i][j]到底部位置的最小的sum。 dp(i,j) = ...

  • 120. Triangle

    Given a triangle, find the minimum path sum from top to b...

网友评论

      本文标题:120. Triangle

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