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.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
package com.bytedance;
/**
* 自顶向下实现记忆化搜索的动态规划
* @author ZFX
* @date2019/5/12 9:22.
*/
public class Leetcode64 {
public static void main(String[] args) {
int[][] arr={{1,3,1},{1,5,1},{4,2,1}};
System.out.println(minPathSum(arr));
}
public static int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] memo = new int[m][n];//记忆化数组
return find(grid,m-1,n-1,memo);
}
public static int find(int[][] grid,int m ,int n ,int[][] memo) {
if(memo[m][n]!=0)
return memo[m][n];
if(m>0&&n>0){
int left = find(grid,m-1,n,memo);
int right =find(grid,m,n-1,memo);
memo[m][n] = Math.min(left,right)+grid[m][n];
return memo[m][n];
}
if(m==-0&&n==0)
return grid[0][0];
if(n==0) {
memo[m][n] = find(grid, m - 1, n, memo) + grid[m][n];
return memo[m][n];
}
else{
memo[m][n] = find(grid,m,n-1,memo)+grid[m][n];
return memo[m][n];
}
}
}