标签:ber int leetcode ++ output rip func color asc
最小路径和。题意是给一个二维矩阵,每个格子上都有一个非负整数。请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。例子,
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.
这是DP的入门题目,直接给代码了。
时间O(mn)
空间O(1)
Java实现
1 class Solution { 2 public int minPathSum(int[][] grid) { 3 for (int i = 0; i < grid.length; i++) { 4 for (int j = 0; j < grid[0].length; j++) { 5 if (i == 0 && j != 0) { 6 grid[i][j] += grid[i][j - 1]; 7 } 8 if (j == 0 && i != 0) { 9 grid[i][j] += grid[i - 1][j]; 10 } 11 if (i != 0 && j != 0) { 12 grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 13 } 14 } 15 } 16 return grid[grid.length - 1][grid[0].length - 1]; 17 } 18 }
JavaScript实现
1 /** 2 * @param {number[][]} grid 3 * @return {number} 4 */ 5 var minPathSum = function (grid) { 6 for (let i = 0; i < grid.length; i++) { 7 for (let j = 0; j < grid[0].length; j++) { 8 if (i == 0 && j != 0) { 9 grid[i][j] += grid[i][j - 1]; 10 } 11 if (j == 0 && i != 0) { 12 grid[i][j] += grid[i - 1][j]; 13 } 14 if (i != 0 && j != 0) { 15 grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 16 } 17 } 18 } 19 return grid[grid.length - 1][grid[0].length - 1]; 20 };
[LeetCode] 64. Minimum Path Sum
标签:ber int leetcode ++ output rip func color asc
原文地址:https://www.cnblogs.com/aaronliu1991/p/12545248.html