这周依然是动态规划的题目~~~先贴原题:
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, wheren is the total number of rows in the triangle.
分析:一开始拿到题目,我想的是,从上往下,然后在最后一层判断哪个最小,但是这样的话要做好多操作!!!因为虽然最后一层就n个元素,但是要想产生最小值,要进行的操作实在太多了,分岔路也很多,工作量很大。但是从下往上呢,就会使得状态转移方程比较容易写。因为如果要找到这一层的最小值,只需要相应的找到下一层的最小值,然后加上这一层的值就好。
即:triangle[i][j] += min{ triangle[i+!][j] , triangle[i+1][j+1]};
下面贴出代码:
#include<vector>
#include<iostream>
#include<math.h>
using namespace std;
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if (triangle.size() > 1) {
for (int i = triangle.size() - 2; i >= 0; i--) {
for (int j = 0; j < triangle[i].size(); j++) {
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]);
}
}
}
return triangle[0][0];
}
int min(int a, int b) {
if (a <= b)
return a;
else
return b;
}
};
效率图:
可以看出,其实就是对这个二维数组遍历了一遍,所以时间复杂度为O(n);空间复杂度申请了一个i,一个j,所以为O(1)