110. 最小路径和

描述

给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。

注意事项

你在同一时间只能向下或者向右移动一步

代码

public class Solution {
    /*
     * @param grid: a list of lists of integers
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    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[][] sum = new int[m][n];
        
        sum[0][0] = grid[0][0];
        for (int i = 1; i < m; i++) {
            sum[i][0] = grid[i][0] + sum[i - 1][0];
        }
        for (int i = 1; i < n; i++) {
            sum[0][i] = grid[0][i] + sum[0][i - 1];
        }
        
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
            }
        }
        
        return sum[m - 1][n - 1];
    }
}
  1. 没看懂
public class Solution {
    /**
     * @param grid: a list of lists of integers.
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    public int minPathSum(int[][] A) {
        if (A == null || A.length == 0 || A[0].length == 0) {
            return 0;
        }
        
        int m = A.length, n = A[0].length;
        int[][] f = new int[2][n];
        int old, now = 0;
        
        for (int i = 0; i < m; ++i) {
            old = now;
            now = 1 - now;
            for (int j = 0; j < n; ++j) {
                int min = -1;
                if (i > 0 && (min == -1 || f[old][j] < min)) {
                    min = f[old][j];
                }
                if (j > 0 && (min == -1 || f[now][j-1] < min)) {
                    min = f[now][j-1];
                }
                
                if (min == -1) {
                    min = 0;
                }
                
                f[now][j] = min + A[i][j];
            }
        }
        
        return f[now][n-1];
    }
}

你可能感兴趣的:(110. 最小路径和)