题目 | OJ地址 | 目录 |
Triangle |
https://oj.leetcode.com/problems/triangle/ |
3.1 |
Maximum Subarray |
https://oj.leetcode.com/problems/maximum-subarray/ |
3.2 |
Palindrome Partitioning II |
https://oj.leetcode.com/problems/palindrome-partitioning-ii/ |
3.3 |
Minimum Path Sum |
https://oj.leetcode.com/problems/minimum-path-sum/ |
3.4 |
Maximal Rectangle |
https://oj.leetcode.com/problems/maximal-rectangle/ |
3.5 |
Interleaving String |
https://oj.leetcode.com/problems/interleaving-string/ |
3.6 |
Edit Distance |
https://oj.leetcode.com/problems/edit-distance/ |
3.7 |
Decode Ways |
https://oj.leetcode.com/problems/decode-ways/ |
3.8 |
Best Time to Buy and Sell StocI&II&III |
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/ |
3.9 |
Scramble String |
https://oj.leetcode.com/problems/scramble-string/ |
3.10 |
Distinct Subsequences |
https://oj.leetcode.com/problems/distinct-subsequences/ |
3.11 |
Word Break I&II |
https://oj.leetcode.com/problems/word-break/ |
3.12 |
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[ [2], [3,4], [6,5,7], [4,1,8,3] ]
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 =
11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
int minimumTotal(vector<vector<int> > &triangle) { int row=triangle.size(); //行,第row行的元素有row个 vector<vector<int> > f(triangle); //用f[m][n]记录从triangle[m][n]出发到叶子节点的最短路径和。也可以直接用triangle代替f,但会改变triangle for(int x=row-2;x>=0;x--) for(int y=0;y<=x;y++) f[x][y]=min(f[x+1][y],f[x+1][y+1])+triangle[x][y]; return f[0][0]; }
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { int row=triangle.size(); //行 vector<vector<int> > f(triangle); //f[m][n]表示从triangle[m][n]出发到叶子节点的最短路径和 for(int m=0;m<row-1;m++) for(int n=0;n<=m;n++) f[m][n]=INT_MAX; //与自底向上的方法不同,备忘录法必须将其初始化为标识值,以便“查找备忘录” f[row-1]=triangle[row-1]; //最后一行保持原值 return dp(0,0,triangle,f); //从根出发 } private: int dp(int x,int y,vector<vector<int> > &triangle,vector<vector<int> > &f){ if(f[x][y]!=INT_MAX) return f[x][y]; //查找备忘录,如果已经计算过,直接返回,避免重复计算 f[x][y]=min(dp(x+1,y,triangle,f),dp(x+1,y+1,triangle,f))+triangle[x][y]; return f[x][y]; } };
原文地址:http://blog.csdn.net/u012162613/article/details/41428119