Leetcode 64. Minimum Path Sum

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/84899574

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Minimum Path Sum

2. Solution

  • Version 1
class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>> path(m, vector<int>(n));
        path[0][0] = grid[0][0];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i > 0 && j > 0) {
                    path[i][j] = min(path[i - 1][j], path[i][j - 1]) + grid[i][j];
                }
                else if(i < 1 && j > 0) {
                    path[i][j] = path[i][j - 1] + grid[i][j];
                }
                else if(i > 0 && j < 1) {
                    path[i][j] = path[i - 1][j] + grid[i][j];
                }
            }
        }
        return path[m - 1][n - 1];
    }
};
  • Version 2
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] = min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];
                }
                else if(i < 1 && j > 0) {
                    grid[i][j] = grid[i][j - 1] + grid[i][j];
                }
                else if(i > 0 && j < 1) {
                    grid[i][j] = grid[i - 1][j] + grid[i][j];
                }
            }
        }
        return grid[m - 1][n - 1];
    }
};

Reference

  1. https://leetcode.com/problems/minimum-path-sum/description/
阅读更多

扫码向博主提问

SnailTyan

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • 深度学习
  • PyTorch
  • OCR
  • Docker
  • Caffe
去开通我的Chat快问

没有更多推荐了,返回首页