https://oj.leetcode.com/problems/triangle/
一个三角形,类似于杨辉三角的形状,求从上到下最小的路径和,但走每一步都得是相邻的。
动态规划,从下到上一层层来。
sum[i] = min{sum[i]+triangle[i][j],sum[i+1]+triangle[i][j]}
有一个保存每一个点数值的过程。
#include <iostream> #include <vector> using namespace std; class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { int row = triangle.size(); if(row == 0) return 0; if(row == 1) return triangle[0][0]; //initialize vector<int> sum; sum.resize(row); for(int i = 0;i<triangle[row-1].size();i++) sum[i] = triangle[row-1][i]; for(int i = row-2;i>=0;i--) { for(int j = 0;j<=i;j++) { int min1 = sum[j]<sum[j+1]?sum[j]:sum[j+1]; sum[j] = min1 + triangle[i][j]; } } return sum[0]; } }; int main() { class Solution myS; vector<int> v1; v1.push_back(-1); vector<int> v2; v2.push_back(-2); v2.push_back(-3); vector<int> v3; v3.push_back(6); v3.push_back(5); v3.push_back(7); vector<int> v4; v4.push_back(4); v4.push_back(1); v4.push_back(8); v4.push_back(3); vector<vector<int> > num; num.push_back(v1); num.push_back(v2); num.push_back(v3); num.push_back(v4); cout<<myS.minimumTotal(num); return 0; }