Given a triangle, find the minimum path sum from top to bottom. Each step of the 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 11
is (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus Point If you be able to does this using only O(n) extra space, where n is the total Number of rows in the triangle.
Code: Space Complexity O (n2), can be improved.
classSolution { Public: intMinimumtotal (vector<vector<int> > &triangle) { introw=triangle.size (); intcol=triangle[row-1].size (); intDp[row][col]; Memset (DP,0,sizeof(DP)); intsum1=0;intSum2=0;intindex=0; intres= (~ (unsigned)1) >>1; for(inti =0; i < row; ++i) {sum1+=triangle[i][0]; Sum2+=Triangle[i][index]; dp[i][0]=sum1; Dp[i][index]=sum2; ++index; } for(inti =1; i < row; ++i) { for(intj =1; J < Triangle[i].size ()-1; ++j) {Dp[i][j]=min (dp[i-1][j],dp[i-1][j-1])+Triangle[i][j]; } } for(intI=0; i<col;++i) { if(dp[row-1][i]<res) res=dp[row-1][i]; } returnRes; }};
Improvement : Because each time only the last result, directly in the same place, the space complexity O (n), the result is retained with temp, and using the last result DP, after the completion of this time, directly with the temp overwrite DP, and then the next time.
Code:
classSolution { Public: intMinimumtotal (vector<vector<int> > &triangle) { if(Triangle.empty ())return 0; introw=triangle.size (); intcol=triangle[row-1].size (); Vector<int> dp (COL,0); Vector<int> Temp (col,0); intsum1=0;intSum2=0;intindex=0; intres= (~ (unsigned)1) >>1; dp[0]=triangle[0][0]; for(inti =1; i < row; ++i) {temp.resize (col,0); for(intj =0; J < Triangle[i].size (); ++j) { if(j==0) Temp[j]=dp[j]+Triangle[i][j]; Else if(J==triangle[i].size ()-1) Temp[j]=dp[j-1]+Triangle[i][j]; ElseTemp[j]=min (dp[j-1],DP[J]) +Triangle[i][j]; } DP=temp; } for(intI=0; i<col;++i) { if(dp[i]<res) res=Dp[i]; } returnRes; }};
Triangle (DP)