LeetCode 64. 最小路径和

LeetCode 64. 最小路径和_第1张图片

 思路:其实和前两道 62 63 求不同路径相似,定位位置grid[i][j]比较grid[i-1][j]和grid[i][j-1] 谁更小就和谁相加。

public static int minPathSum(int[][] grid) {
        if(grid.length==0 || grid[0].length==0)return 0;
        int result = 0;
        int r = grid.length ,c= grid[0].length;
        int[][] a = new int[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if(i==0&&j==0){
                    a[i][j]=grid[i][j];
                }else if(i==0){
                    a[i][j]+=a[i][j-1]+grid[i][j];
                }else if(j==0){
                    a[i][j]+=a[i-1][j]+grid[i][j];
                }else {
                    a[i][j]+=a[i-1][j] > a[i][j-1] ? a[i][j-1] : a[i-1][j];
                    a[i][j]+=+grid[i][j];
                }
            }
        }
        return a[r-1][c-1];
    }

 

你可能感兴趣的:(算法,LeetCode,64.,最小路径和)