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).
思路:这道题主要使用动态规划的来解决问题。
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { int nSize=triangle.size(); if(nSize<=0) return 0; int dp[1000]; memset(dp,INT_MAX,sizeof(dp)); dp[0]=triangle[0][0]; for(int i=1;i<nSize;i++) { int m=triangle[i].size()-1; for(int j=m;j>=0;j--) { if(j==0) dp[j]=dp[j]+triangle[i][j]; else if(j==m) dp[j]=dp[j-1]+triangle[i][j]; else dp[j]=min(dp[j],dp[j-1])+triangle[i][j]; } } int sum=INT_MAX; for(int i=0;i<nSize;i++) { sum=((sum>dp[i])?dp[i]:sum); } return sum; } };