zoukankan      html  css  js  c++  java
  • LintCode: Minimum Path Sum

    C++,

    time: O(m*n)

    space: O(m*n)

     1 class Solution {
     2 public:
     3     /**
     4      * @param grid: a list of lists of integers.
     5      * @return: An integer, minimizes the sum of all numbers along its path
     6      */
     7     int minPathSum(vector<vector<int> > &grid) {
     8         // write your code here
     9         int m = grid.size(), n = grid[0].size();
    10         vector<vector<int> > dp(m, vector<int>(n));
    11         for (int i = 0; i < m; i++) {
    12             for (int j = 0; j < n; j++) {
    13                 if (i == 0) {
    14                     if (j == 0) {
    15                         dp[i][j] = grid[i][j];
    16                     } else {
    17                         dp[i][j] = dp[i][j-1] + grid[i][j];
    18                     }
    19                 } else if (j == 0) {
    20                     dp[i][j] = dp[i-1][j] + grid[i][j];
    21                 } else {
    22                     dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
    23                 }
    24             }
    25         }
    26         return dp[m-1][n-1];
    27     }
    28 };

    C++,

    time: O(m*n)

    space: O(m)

     1 class Solution {
     2 public:
     3     /**
     4      * @param grid: a list of lists of integers.
     5      * @return: An integer, minimizes the sum of all numbers along its path
     6      */
     7     int minPathSum(vector<vector<int> > &grid) {
     8         // write your code here
     9         int m = grid.size(), n = grid[0].size();
    10         vector<int> dp(n);
    11         for (int i = 0; i < m; i++) {
    12             for (int j = 0; j < n; j++) {
    13                 if (i == 0) {
    14                     if (j == 0) {
    15                         dp[j] = grid[i][j];
    16                     } else {
    17                         dp[j] = dp[j-1] + grid[i][j];
    18                     }
    19                 } else if (j == 0) {
    20                     dp[j] = dp[j] + grid[i][j];
    21                 } else {
    22                     dp[j] = min(dp[j], dp[j - 1]) + grid[i][j];
    23                 }
    24             }
    25         }
    26         return dp[n-1];
    27     }
    28 };
  • 相关阅读:
    使用WLC+Portal完成认证
    WLAN PSK认证
    Bug搬运工-flexconnect AP losing Vlan mapping and fall back to default vlan
    Catalyst 9400配置StackWise Virtual
    如何在Wave2 AP上更改时区
    VMware Workstation导入ova镜像文件时报错?
    Password Recovery on Cisco Catalyst 3850
    Mobility Express初始化和升级
    C9300升级-TFTP
    查看WLC的SFP模块信息
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5000605.html
Copyright © 2011-2022 走看看