#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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.分析:这是动态规划问题。设dp[i]表示从根节点到当前第i行时获取的最大和dp[0]=底部的值是确定的,那么我们可以自底向上来做,设当前数为A[i][j],那么A[i][j]只可能从A[i+1][j]或者A[i+1][j+1]中选择下一个要遍历的元素设dp[i][j]表示从元素A[i][j]到达最下一面一层的时候的所有和的最小值dp[i][j] = min(dp[i+1][j] , dp[i+1][j+1]) + A[i][j]假设总共有row行dp[row-1][j] = A[i][j],所求结果就是dp[0][0]输入:4(行数)1(当前行中元素个数) 22 3 436 5 744 1 8 3输出:11关键:1 dp[i]表示莫一行第i个元素到最底部的和的最小值用动态规划,进行递推,从最下面一行开始,当前行和下面行的对应两个数的结果,并提供给上一行使用即可。for(int i = row - 2; i >= 0 ; i--){ len = triangle.at(i).size(); //最后一个元素要取到 for(int j = 1 ; j <= len ; j++) { //更新当前行,当前行的元素,是该元素到底部的最短距离 dp.at(j-1) = min( dp.at(j-1) , dp.at(j)) + triangle.at(i).at(j-1); }}*/class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { if(triangle.empty()) { return 0; } int row = triangle.size(); //由于是三角形,最大列数在最后一行 int col = triangle.at(row - 1).size(); vector< int > dp( col , 0 ); int len = triangle.at(row - 1).size(); //初始化最下面一行的值 for(int i = 0 ; i < len ; i++) { dp.at(i) = triangle.at(row-1).at(i); } //用动态规划,进行递推,从最下面一行开始,当前行和下面行的对应两个数的结果,并提供给上一行使用即可 for(int i = row - 2; i >= 0 ; i--) { len = triangle.at(i).size(); //最后一个元素要取到 for(int j = 1 ; j <= len ; j++) { //更新当前行,当前行的元素,是该元素到底部的最短距离 dp.at(j-1) = min( dp.at(j-1) , dp.at(j)) + triangle.at(i).at(j-1); } } return dp.at(0); }};void PRocess(){ vector<vector<int> > nums; int value; int row; int col; Solution solution; while(cin >> row ) { nums.clear(); for(int i = 0 ; i < row ; i++) { cin >> col; vector<int> datas; for(int j = 0 ; j < col ;j++) { cin >> value; datas.push_back(value); } nums.push_back(datas); } int result = solution.minimumTotal(nums); cout << result << endl; }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新闻热点
疑难解答