LeetCode:64. Minimum Path Sum(最小路径问题)

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.

方法1:遇到这种题目无脑动态规划

class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (i == 0 && j == 0){
                    continue;
                }	
				if (i == 0){
                    grid[0][j] += grid[0][j - 1];
                }else if (j == 0){
					grid[i][0] += grid[i - 1][0];
                }else{
                    grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
                }		
			}
		}
		return grid[m - 1][n - 1];        
    }
}

时间复杂度:O(m.n)

空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84979265