Skip to content

Latest commit

 

History

History
95 lines (79 loc) · 2.45 KB

20200713-最小路径和.md

File metadata and controls

95 lines (79 loc) · 2.45 KB

每天一道leetCode

信息卡片

题目描述

给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

说明:每次只能向下或者向右移动一步。

示例:

输入:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。

参考答案

空间复杂度O(n)版

这道题是在不同路径基础上改一改就行了

dp[i][j] = dp[i][j], i = 0, j = 0
           dp[i][j] + dp[i][j - 1], i = 0
           dp[i][j] + dp[i - 1][j], j = 0
           dp[i][j] + Math.min(dp[i][j - 1], dp[i - 1][j]), i != 0, j != 0
class Solution {
    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        int[] cur = new int[n];
        for (int j = 0; j < n; j++) {
            cur[j] = j == 0 ? grid[0][0] : cur[j - 1] + grid[0][j];
        }
        for (int i = 1; i < m; i++) {
            for(int j = 0; j < n; j++) {
                cur[j] = j == 0 ? cur[j] + grid[i][0] : Math.min(cur[j], cur[j - 1]) + grid[i][j];
            }
        }
         return cur[n - 1];
    }
}

空间复杂度O(1)版

直接在原数组上覆盖即可

class Solution {
    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        
        for (int j = 0; j < n; j++) {
            grid[0][j] = j == 0 ? grid[0][0] : grid[0][j - 1] + grid[0][j];
        }
        for (int i = 1; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if (i == 0 && j == 0) {
                    continue;
                } else if (i == 0) {
                    grid[i][j] = grid[i][j - 1] + grid[i][j];
                } else if (j == 0) {
                    grid[i][j] = grid[i - 1][j] + grid[i][j];
                } else {
                    grid[i][j] = Math.min(grid[i -1][j], grid[i][j - 1]) + grid[i][j];
                }
            }
        }
         return grid[m - 1][n - 1];
    }
}