【题目】
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.
【分析】
这是一道动态规划的题目,求一个三角形二维数组从顶到低端的最小路径和。
我们从低端向顶端计算。设状态为 S[i][j]表示从从位置 ( i, j ) 出发,到最低端路径的最小和
状态转移方程:
S[i][j] = min(S[i+1][j] + S[i+1][j+1]) +S[i][j]
S[0][0]就是要求解的答案。
时间复杂度 O(n^2) ,空间复杂度 O(1)
【代码】
/**------------------------------------
* 日期:2015-02-03
* 作者:SJF0115
* 题目: 120.Triangle
* 网址:https://oj.leetcode.com/problems/triangle/
* 结果:AC
* 来源:LeetCode
* 博客:
---------------------------------------**/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int size = triangle.size();
// down-to-top
// 第i层
for(int i = size - 2;i >= 0;--i){
// 第i层的第j个元素
for(int j = 0;j <= i;++j){
triangle[i][j] += min(triangle[i+1][j],triangle[i+1][j+1]);
}//for
}//for
return triangle[0][0];
}
};
int main(){
Solution s;
vector<vector<int> > triangle = {{2},{3,4},{6,5,3},{4,1,8,3}};
int result = s.minimumTotal(triangle);
// 输出
cout<<result<<endl;
return 0;
}
【思路二】
一位网友说:虽然是O(1)的空间复杂度,但其实破坏了三角形本身啊。如果算上占用的三角形本身的空间,实际使用的空间复杂度应该算O(N^2)了。
只求值不求本身的时候,都是可以用空间轮转这个办法的。如LCS、走棋盘等等一批问题,都可以这么节省。
从上面思路的状态转移方程中看出:S[i][j] = min(S[i+1][j] + S[i+1][j+1]) +S[i][j]
S[i][j]只与下一行的第j个元素和第j+1个元素相关,i的关系是固定的,因此我们可以省去这一维。
开辟O(N)的数组,然后规划的时候使用S[j] = min(S[j+1], S[j) +Triangle[i][j]就可以了。
【代码二】
/*------------------------------------
* 日期:2015-02-03
* 作者:SJF0115
* 题目: 120.Triangle
* 网址:https://oj.leetcode.com/problems/triangle/
* 结果:AC
* 来源:LeetCode
* 博客:
---------------------------------------*/
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int size = triangle.size();
vector<int> next(triangle.back());
// down-to-top
// 第i层
for(int i = size - 2;i >= 0;--i){
// 第i层的第j个元素
for(int j = 0;j <= i;++j){
next[j] = min(next[j],next[j+1]) + triangle[i][j];
}//for
}//for
return next[0];
}
};