zoukankan      html  css  js  c++  java
  • Minimum Path Sum——LeetCode

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

    Note: You can only move either down or right at any point in time.

    题目大意:给定一个m*n矩阵,都是非负数字,找到一条路径从左上角到右下角路径和最小,路径只能向右或向下走。

    解题思路:基础dp题,用一个二维数组记录到当前位置最小路径和,取决于当前位置的左边和上边的最小路径和,注意处理矩阵最左边和最上边的。

        public int minPathSum(int[][] grid) {
            if (grid == null || grid[0].length == 0)
                return 0;
            int rowLen = grid.length;
            int colLen = grid[0].length;
            int[][] sum = new int[rowLen][colLen];
            sum[0][0] = grid[0][0];
            for (int i = 0; i < rowLen; i++) {
                for (int j = 0; j < colLen; j++) {
                    if (i > 0 && j > 0)
                        sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
                    else if (i == 0 && j > 0) {
                        sum[i][j] = sum[i][j - 1] + grid[i][j];
                    } else if (i > 0 && j == 0) {
                        sum[i][j] = sum[i - 1][j] + grid[i][j];
                    }
                }
            }
            return sum[rowLen - 1][colLen - 1];
        }
  • 相关阅读:
    学习笔记_2012_4_13垃圾回收原理与String类的学习
    第五篇
    HTML练习代码
    上课第一天base关键字
    第四篇
    firebug使用指南
    HTML5的新特性
    UML建模
    CSS学习总结
    (转载)About me [my way]
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4441927.html
Copyright © 2011-2022 走看看