LeetCode OJ-64.Minimum Path Sum(DP)

LeetCode OJ-64.Minimum Path Sum(DP)

题目描述

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.

Subscribe to see which companies asked this question

题目理解

​ 与LeetCode 62类似,使用动态规划可以很好地解决。同样只能向右向下移动,起点是左上角,终点是右下角起点是左上角。当左边或者上边没有格子的时候,到当前位置的路径唯一,所以直接用上一个状态加上当前位置的数字即可。因此可以定义dp[i][j]为到(i, j)位置的所有路径中的数相加的最小值,状态方程为:dp[i][j] = { grid[0][0], i = 0 && j = 0 } | { dp[i - 1][0] + grid[i][0], i > 0 && j = 0 } | { dp[0][j - 1] + grid[0][j], j > 0 && i = 0 } | { dp[i][j] = MIN(dp[i - ][j], dp[i][j - 1]) + grid[i][j], i > 0 && j > 0 }.

Code

#define MIN(m, n) ( (m < n) ? m : n )

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

        for (i = 1; i < m; ++i) {
            for (j = 1; j < n; ++j) {
                rec[i][j] = MIN(rec[i - 1][j], rec[i][j - 1]) + grid[i][j];
            }
        }

        return rec[m - 1][n - 1]; 
    }
};

你可能感兴趣的:(OJ-DP,leetcode,ACM,OJ,dp,最小路径和)