LeetCode64:最小路径和

题目描述

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

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

示例:

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

方法一:
package LeetCode;

public class DT64 {
    public static void main(String[] args) {
        DT64 dt = new DT64();
        int[][] grid = {{1,3,1},{1,5,1},{4,2,1}};
        int res = dt.minPathSum(grid);
        System.out.println(res);
    }

    public int minPathSum(int[][] grid) {

        int n = grid.length;
        int m = grid[0].length;

        int[][] dp = new int[n][m];
        int res = backTrack(grid,dp,0,0);

        return res;
    }

    public int backTrack(int[][] grid,int[][] dp,int i,int j){

        if(i == grid.length - 1 && j == grid[0].length - 1 ) {
            return grid[i][j];
        }

        if(i == grid.length || j == grid[0].length) {
            return Integer.MAX_VALUE;
        }

        if(dp[i][j] > 0) {
            return dp[i][j];
        }

        dp[i][j] = Math.min(backTrack(grid,dp,i + 1,j),backTrack(grid,dp,i,j + 1)) + grid[i][j];
        return dp[i][j];
    }
}
方法二:
package LeetCode;

public class DT64Demo {

    public static void main(String[] args) {
        DT64Demo dt = new DT64Demo();
        int[][] grid = {{1,3,1},{1,5,1},{4,2,1}};
        int res = dt.minPathSum(grid);
        System.out.println(res);
    }


    public int minPathSum(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        int[][] dp = new int[n][m];
        int res = backTrack(grid,dp,n - 1,m - 1);

        return res;
    }

    public int backTrack(int[][] grid,int[][] dp,int i,int j){

        if(i == 0 && j == 0) {
            return grid[i][j];
        }

        if(i < 0 || j < 0) {
            return Integer.MAX_VALUE;
        }

        if(dp[i][j] > 0) {
            return dp[i][j];
        }

        dp[i][j] = grid[i][j] + Math.min(backTrack(grid,dp,i - 1,j),backTrack(grid,dp,i,j - 1));

        return dp[i][j];
    }
}

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