leetcode 64. Minimum Path Sum

来源:互联网 发布:教乐器软件下载 编辑:程序博客网 时间:2024/05/21 13:23

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.

还是这道题的变形:
这里写图片描述
上次在每个格子里放01 这次放正整数
之前dp[i][j] 表示路径的数目 采用dp[i+1][j]+dp[i][j+1]
这个dp[i][j]表示路径长度 所以要采用 max(dp[i+1][j] ,dp[i][j+1] ) +grid[i][j]

public int minPathSum(int[][] grid) {        int m = grid.length;        if(m == 0) return 0;        int n = grid[0].length;        int[][] dp = new int[m][n];        int i,j;        for(int index = m*n-1;index >= 0;index--){            i = index / n;            j = index % n;            if(index == m*n-1) dp[i][j] = grid[i][j];            else{                dp[i][j] = grid[i][j];                if(i+1 >= m) dp[i][j] += dp[i][j+1];                else if(j+1 >= n) dp[i][j] += dp[i+1][j] ;                else{                    dp[i][j] += Integer.min(dp[i+1][j], dp[i][j+1]);                }            }        }//      for(i = 0;i < m;i++){//          for(j = 0;j < n;j++)//              System.out.printf("%4d",dp[i][j]);//          System.out.println();//      }        return dp[0][0];    }
0 0
原创粉丝点击