64. Minimum Path Sum LeetCode
2016-02-14 18:48
525 查看
题意:给出一个NxM的矩阵,每个格子有一个非负数,从左上角走到右下角,每次只能往下或者往右走一格,求一条路径,使得走过的格子数字之和最小。
题解:dp。dp[i][j] 表示从0,0走到i行j列这个格子的最小数字和。
dp[i][j] = min(dp[i - 1][j],dp[i][j - 1]) + num[i][j].
题解:dp。dp[i][j] 表示从0,0走到i行j列这个格子的最小数字和。
dp[i][j] = min(dp[i - 1][j],dp[i][j - 1]) + num[i][j].
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int n = grid.size(); int m = grid[0].size(); int dp [m]; dp[0][0] = grid[0][0]; for(int i = 1; i < n; i++) dp[i][0] = dp[i - 1][0] + grid[i][0]; for(int i = 1; i < m; i++) dp[0][i] = dp[0][i - 1] + grid[0][i]; for(int i = 1; i < n; i++) for(int j = 1; j < m; j++) dp[i][j] = min(dp[i][j-1],dp[i-1][j]) + grid[i][j]; return dp[n - 1][m - 1]; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解