leetcode 64 最小路径和
原题链接
https://leetcode.cn/problems/minimum-path-sum/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public int minPathSum(int[][] grid) { int n = grid.length; int m = grid[0].length; int [][] dp = new int [n][m]; dp[0][0] = grid[0][0]; for(int i = 0; i < n ; i++){ for(int j = 0 ; j < m ; j++){ if(i == 0 && j == 0){ continue; }
else if(i == 0){ dp[i][j] = dp[i][j - 1] + grid[i][j]; } else if(j == 0){ dp[i][j] = dp[i - 1][j] + grid[i][j]; }else{ dp[i][j] = Math.min(dp[i - 1][j] + grid[i][j],dp[i][j - 1] + grid[i][j]); } } }
return dp[n - 1][m - 1]; } }
|