题目:
最小路径和
给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。
样例
注意
你在同一时间只能向下或者向右移动一步
解题:
这个和求三角形的最小路径的差不多,这里是个矩阵,第一列和第一行要单独处理,每一点的值等于自身的值加上上一点的值,对于中间节点:grid[i][j] + = min( grid[i-1][j] , grid[i][j-1]) ,也就是说,i j 点的值只能是其左侧的点或者上侧的点加过来,这个时间复杂度比较高O(N2)
Java程序:
public class Solution { /** * @param grid: a list of lists of integers. * @return: An integer, minimizes the sum of all numbers along its path */ public int minPathSum(int[][] grid) { // write your code here int m = grid.length; if(m == 0 ) return 0; int n = grid[0].length; if( n==0 ) return 0; for(int i=1 ; i<n; i++ ){ grid[0][i] += grid[0][i-1]; } for( int i= 1;i< m; i++ ){ grid[i][0] += grid[i-1][0]; } for(int i=1; i< m ; i++){ for(int j = 1;j< n; j++){ grid[i][j] += Math.min(grid[i-1][j],grid[i][j-1]); } } return grid[m-1][n-1]; } }
Python程序:
class Solution: """ @param grid: a list of lists of integers. @return: An integer, minimizes the sum of all numbers along its path """ def minPathSum(self, grid): # write your code here m = len(grid) if m == 0: return 0 n = len(grid[0]) if n==0: return 0 for i in range(m): for j in range(n): if i==0 and j!=0: grid[i][j] += grid[i][j-1] elif j==0 and i!=0: grid[i][j] += grid[i-1][j] elif j!=0 and i!=0: grid[i][j] += min(grid[i-1][j] , grid[i][j-1]) return grid[m-1][n-1]
时间: 2024-12-20 08:49:46