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

解題思路:
狀態定義:
設 dpdpdp 爲大小 m×nm \times nm×n 矩陣,其中 dp[i][j]dp[i][j]dp[i][j] 的值代表直到走到 (i,j)(i,j)(i,j) 的最小路徑和。
轉移方程:
題目要求,只能向右或向下走,換句話說,當前單元格 (i,j)(i,j)(i,j) 只能從左方單元格 (i−1,j)(i-1,j)(i−1,j) 或上方單元格 (i,j−1)(i,j-1)(i,j−1) 走到,因此只需要考慮矩陣左邊界和上邊界。
走到當前單元格 (i,j)(i,j)(i,j) 的最小路徑和 === “從左方單元格 (i−1,j)(i-1,j)(i−1,j) 與 從上方單元格 (i,j−1)(i,j-1)(i,j−1) 走來的 兩個最小路徑和中較小的 ” + 當前單元格值 grid[i][j] 。
具體分爲以下 4種情況:
在這裏插入圖片描述
在這裏插入圖片描述

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
           int m=grid.size();
           int n=grid[0].size();
           for(int i=0;i<m;i++)
           {
               for(int j=0;j<n;j++)
               {
                   if(i==0&&j!=0)
                   {
                       grid[i][j]+=grid[i][j-1];
                   }
                   else if(j==0&&i!=0)
                   {
                       grid[i][j]+=grid[i-1][j];
                   }
                   else if(i!=0&&j!=0)
                   {
                       grid[i][j]+=(grid[i-1][j]>grid[i][j-1]?grid[i][j-1]:grid[i-1][j]);
                   }
               }
           }
           return grid[m-1][n-1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章