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 };
复制代码

 

本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5000605.html,如需转载请自行联系原作者

相关文章
|
存储 人工智能 C++
【PAT甲级 - C++题解】1104 Sum of Number Segments
【PAT甲级 - C++题解】1104 Sum of Number Segments
92 0
|
C++
【PAT甲级 - C++题解】1145 Hashing - Average Search Time
【PAT甲级 - C++题解】1145 Hashing - Average Search Time
85 0
LeetCode 64. Minimum Path Sum
给定m x n网格填充非负数,找到从左上到右下的路径,这最小化了沿其路径的所有数字的总和。 注意:您只能在任何时间点向下或向右移动。
112 0
LeetCode 64. Minimum Path Sum
|
Go
LeetCode 124. Binary Tree Maximum Path Sum
给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
76 0
LeetCode 124. Binary Tree Maximum Path Sum