# Minimum Path Sum
- tags: [[DP_Matrix](# "根据动态规划解题的四要素,矩阵类动态规划问题通常可用 f[x][y] 表示从起点走到坐标(x,y)的值")]
### Source
- lintcode: [(110) Minimum Path Sum](http://www.lintcode.com/en/problem/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.
~~~
### 题解
1. State: f[x][y] 从坐标(0,0)走到(x,y)的最短路径和
1. Function: f[x][y] = (x, y) + min{f[x-1][y], f[x][y-1]}
1. Initialization: f[0][0] = A[0][0], f[i][0] = sum(0,0 -> i,0), f[0][i] = sum(0,0 -> 0,i)
1. Answer: f[m-1][n-1]
注意最后返回为f[m-1][n-1]而不是f[m][n].
首先看看如下正确但不合适的答案,OJ上会出现[TLE](# "Time Limit Exceeded 的简称。你的程序在 OJ 上的运行时间太长了,超过了对应题目的时间限制。")。未使用hashmap并且使用了递归的错误版本。
### C++ [dfs](# "Depth-First Search, 深度优先搜索") without hashmap: ~~Wrong answer~~
~~~
class Solution {
public:
/**
* @param grid: a list of lists of integers.
* @return: An integer, minimizes the sum of all numbers along its path
*/
int minPathSum(vector<vector<int> > &grid) {
if (grid.empty()) {
return 0;
}
const int m = grid.size() - 1;
const int n = grid[0].size() - 1;
return helper(grid, m, n);
}
private:
int helper(vector<vector<int> > &grid_in, int x, int y) {
if (0 == x && 0 == y) {
return grid_in[0][0];
}
if (0 == x) {
return helper(grid_in, x, y - 1) + grid_in[x][y];
}
if (0 == y) {
return helper(grid_in, x - 1, y) + grid_in[x][y];
}
return grid_in[x][y] + min(helper(grid_in, x - 1, y), helper(grid_in, x, y - 1));
}
};
~~~
使用迭代思想进行求解的正确实现:
### C++ Iterative
~~~
class Solution {
public:
/**
* @param grid: a list of lists of integers.
* @return: An integer, minimizes the sum of all numbers along its path
*/
int minPathSum(vector<vector<int> > &grid) {
if (grid.empty() || grid[0].empty()) {
return 0;
}
const int M = grid.size();
const int N = grid[0].size();
vector<vector<int> > ret(M, vector<int> (N, 0));
ret[0][0] = grid[0][0];
for (int i = 1; i != M; ++i) {
ret[i][0] = grid[i][0] + ret[i - 1][0];
}
for (int i = 1; i != N; ++i) {
ret[0][i] = grid[0][i] + ret[0][i - 1];
}
for (int i = 1; i != M; ++i) {
for (int j = 1; j != N; ++j) {
ret[i][j] = grid[i][j] + min(ret[i - 1][j], ret[i][j - 1]);
}
}
return ret[M - 1][N - 1];
}
};
~~~
### 源码分析
1. 异常处理,不仅要对grid还要对grid[0]分析
1. 对返回结果矩阵进行初始化,注意ret[0][0]须单独初始化以便使用ret[i-1]
1. 递推时i和j均从1开始
1. 返回结果ret[M-1][N-1],注意下标是从0开始的
此题还可进行空间复杂度优化,和背包问题类似,使用一维数组代替二维矩阵也行,具体代码可参考 [水中的鱼: [LeetCode] Minimum Path Sum 解题报告](http://fisherlei.blogspot.sg/2012/12/leetcode-minimum-path-sum.html)
优化空间复杂度,要么对行遍历进行优化,要么对列遍历进行优化,通常我们习惯先按行遍历再按列遍历,有状态转移方程 f[x][y] = (x, y) + min{f[x-1][y], f[x][y-1]} 知,想要优化行遍历,那么f[y]保存的值应为第x行第y列的和。由于无行下标信息,故初始化时仅能对第一个元素初始化,分析时建议画图理解。
### C++ 1D vector
~~~
class Solution {
public:
/**
* @param grid: a list of lists of integers.
* @return: An integer, minimizes the sum of all numbers along its path
*/
int minPathSum(vector<vector<int> > &grid) {
if (grid.empty() || grid[0].empty()) {
return 0;
}
const int M = grid.size();
const int N = grid[0].size();
vector<int> ret(N, INT_MAX);
ret[0] = 0;
for (int i = 0; i != M; ++i) {
ret[0] = ret[0] + grid[i][0];
for (int j = 1; j != N; ++j) {
ret[j] = grid[i][j] + min(ret[j], ret[j - 1]);
}
}
return ret[N - 1];
}
};
~~~
初始化时需要设置为`INT_MAX`,便于`i = 0`时取`ret[j]`.
- Preface
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Two Lists Sum
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Check if a singly linked list is palindrome
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Unique Binary Search Trees II
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume