leetcode | Minimum Path Sum

Minimum Path Sum : https://leetcode.com/problems/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.


解析:
本题是一个动态规划类型的题目,
求 grid[0][0] 到 grid[rows-1][cols-1]的最小路径和
设m[i][j]表示从grid[0][0]到grid[i][j]的最小路径和,那么

  • m[0][0] = grid[0][0];
  • m[0][j] = m[0][j-1] + grid[0][j];
  • m[i][0] = m[i-1][0] + grid[i][0];
  • m[i][j] = min(m[i-1][j], m[i][j-1]) + gird[i][j];

由上述条件等式,easy写出动态规划的程序:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int rows = grid.size();
        int cols = grid[0].size();
        int result = 0;
        if (rows == 0 || cols == 0)
            return 0;
        int** m = new int*[rows];
        for (int i = 0;i < rows; i++)
            m[i] = new int[cols];
        // 动态规划。从小问题迭代求解  
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (i == 0 && j == 0) {
                    m[i][j] = grid[i][j];
                } else if (i == 0) {
                    m[i][j] = m[i][j-1] + grid[i][j];
                } else if (j == 0) {
                    m[i][j] = m[i-1][j] + grid[i][j];
                } else {
                    m[i][j] = min(m[i-1][j], m[i][j-1]) + grid[i][j];
                }
            }
        }
        result = m[rows-1][cols-1];
        for (int i = 0; i < rows; i++)
            delete m[i];
        delete m;
        m = NULL;
        return result;
    }
};

posted on 2017-08-16 19:52  wgwyanfs  阅读(94)  评论(0编辑  收藏  举报

导航