LeetCode:64. Minimum Path Sum(最小路徑問題)
阿新 • • 發佈:2018-12-21
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)