Leetcode Triangle 相关代码,使用dp方法完成,c++代码如下,并提供简单的测试代码。
#include <iostream>
#include <unordered_set>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int minimumTotal(vector<vector<int> >& triangle) {
if (triangle.size() == 0) {
return 0;
}
int len = triangle.size();
int min;
int pre = 0; // remember the previous re
vector<int> re(len, 0);
re[0] = triangle[0][0];
for (int i = 1; i < len; i ++) {
for (int j = 0; j <= i; j ++) {
// the re[i] has no valid value in the previous line
if (j != i) {
min = re[j] + triangle[i][j];
}
// the re[-1] is invalid, the pre remember the re[j - 1]
if ((j >= 1 && pre + triangle[i][j] < min) || j == i) {
min = pre + triangle[i][j];
}
pre = re[j];
re[j] = min;
}
}
min = re[0];
// find the minimal result in re
for (vector<int>::iterator it = re.begin(); it != re.end(); it ++) {
if (*it < min) {
min = *it;
}
}
return min;
}
};
int main() {
Solution * so = new Solution();
vector<vector<int> > test;
vector<int> a;
a.push_back(-1);
test.push_back(a);
a.clear();
a.push_back(2);
a.push_back(3);
test.push_back(a);
a.clear();
a.push_back(1);
a.push_back(-1);
a.push_back(-3);
test.push_back(a);
cout<<"the minimal result is: "<<so->minimumTotal(test)<<endl;
}