[LeetCode]120.Triangle
【題目】
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];
}
};