# 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