zoukankan      html  css  js  c++  java
  • 19.2.11 [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.
     1 class Solution {
     2 public:
     3     int caluniquePaths(vector<vector<int>>&grid,vector<vector<int>>&mark,int m, int n) {
     4         int down = -1, right = -1;
     5         if (mark[m][n] != -1)return mark[m][n];
     6         int orim = grid.size(), orin = grid[0].size();
     7         if (m > 1)
     8             down = caluniquePaths(grid,mark, m - 1, n);
     9         if (n > 1)
    10             right = caluniquePaths(grid,mark, m, n - 1);
    11         if (down == -1)down = right;
    12         if (right == -1)right = down;
    13         mark[m][n] = grid[orim-m][orin-n]+min(down,right);
    14         return mark[m][n];
    15     }
    16     int minPathSum(vector<vector<int>>& grid) {
    17         int m = grid.size(), n = grid[0].size();
    18         vector<vector<int>>mark(m+1, vector<int>(n+1, -1));
    19         mark[1][1] = grid[m-1][n-1];
    20         return caluniquePaths(grid,mark, m, n);
    21     }
    22 };
    View Code

    用的改的上一题的题解,但偏慢,不如改成dp快,估计是调用比较慢

     1 class Solution {
     2 public:
     3     int minPathSum(vector<vector<int>>& grid) {
     4         int m = grid.size(), n = grid[0].size();
     5         vector<vector<int>>dp(m, vector<int>(n, INT_MAX));
     6         dp[0][0] = grid[0][0];
     7         for(int i=0;i<m;i++)
     8             for (int j = 0; j < n; j++) {
     9                 if (i == 0 && j == 0)continue;
    10                 if (i == 0) {
    11                     dp[i][j] = min(dp[i][j - 1] + grid[i][j], dp[i][j]);
    12                 }
    13                 else if (j == 0) {
    14                     dp[i][j] = min(dp[i - 1][j] + grid[i][j], dp[i][j]);
    15                 }
    16                 else {
    17                     dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j], dp[i][j]);
    18                 }
    19             }
    20         return dp[m - 1][n - 1];
    21     }
    22 };
    View Code
  • 相关阅读:
    Python 标准库 urllib2 的使用细节
    为什么C++编译器不能支持对模板的分离式编译
    source insight插件
    tar命令
    绘制和重绘,有效矩形和无效矩形
    常量表达式
    区间迭代
    lambda函数
    decltype和新的返回值语法
    auto用法
  • 原文地址:https://www.cnblogs.com/yalphait/p/10361215.html
Copyright © 2011-2022 走看看