• leetcode 64. Minimum Path Sum


    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.
    Accepted

    Solution

    在每一个位置[i][j],要么从上面一个位置下来,要么从左边一个位置过来
    所以其动态规划的状态转移方程为
    dp[i][j]=min{dp[i-1][j],dp[i][j-1]} + nowLocation
    注意第一行和第一列的初始化

    class Solution {
    public:
        int minPathSum(vector<vector<int>>& grid) {
           int m = grid[0].size();
    		int n = grid.size();
    		int dp[n + 1][m + 1];
    		for (int i = 0; i <= m; i++)
    			dp[0][i] = 0;
    		for (int i = 0; i <= n; i++)
    			dp[i][0] = 0;
    		for (int i = 1; i <= n; i++)
    			for (int j = 1; j <= m; j++) {
    				if (i == 1)
    					dp[i][j] = dp[i][j - 1] + grid[i - 1][j - 1];
    				else if (j == 1)
    					dp[i][j] = dp[i - 1][j] + grid[i - 1][j - 1];
    				else {
    					dp[i][j] = (dp[i - 1][j] <= dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1]) + grid[i - 1][j - 1];
    				}
    			}
    		return dp[n][m];
        }
    };
    

    参考链接

    leetcoe

    blogs record our growth
  • 相关阅读:
    H
    并查集
    H
    Supermarket (贪心 并查集)
    H
    M
    N-Find a way
    HDU 4035 Maze
    #386. 【UNR #3】鸽子固定器
    P4688 [Ynoi2016]掉进兔子洞
  • 原文地址:https://www.cnblogs.com/qwfand/p/12668883.html
Copyright © 2020-2023  润新知