zoukankan      html  css  js  c++  java
  • [Leetcode 59] 64 Minimum Path Sum

    Problem:

    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.

    Analysis:

    Simple DP problem, always choose the minimum path preceed the current position.

    Code:

     1 class Solution {
     2 public:
     3     int minPathSum(vector<vector<int> > &grid) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int m = grid.size();
     7         int n = grid[0].size();
     8         int tab[m][n];
     9         
    10         tab[0][0] = grid[0][0];
    11         for (int i=1; i<n; i++)
    12             tab[0][i] = tab[0][i-1] + grid[0][i];
    13         
    14         for (int i=1; i<m; i++)
    15             tab[i][0] = tab[i-1][0] + grid[i][0];
    16             
    17         for (int i=1; i<m; i++)
    18             for (int j=1; j<n; j++) {
    19                 tab[i][j] = min(tab[i][j-1], tab[i-1][j]) + grid[i][j];
    20             }
    21         
    22         return tab[m-1][n-1];
    23     }
    24     
    25     int min(int &a, int &b) {
    26         return (a<b)?a:b;
    27     }
    28 };
    View Code
  • 相关阅读:
    1320. Graph Decomposition 夜
    1156. Two Rounds 夜
    1176. Hyperchannels 夜
    1227. Rally Championship 夜
    1450. Russian Pipelines 夜
    1137. Bus Routes 夜
    找回c盘空间
    IDOC
    .落叶无痕水无声
    真正写的第一篇博客吧
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099831.html
Copyright © 2011-2022 走看看