Today no matter, do three leetcode water problem, anger more two blog, also quite good. The two updates today are simple questions for DP solutions.
- The subject requirements are as follows.
Given a triangle, find theMinimum path sum fromTop toBottom. Each step, may move toAdjacent numbers on theRowbelow. For example,given theFollowing triangle[[2], [3,4], [6,5,7], [4,1,8,3]]the Minimum path sum fromTop toBottom is One(i.e.,2+3+5+1= One). Note:bonus PointifYou are able toDo the using only O (n) extraSpace,whereN is theTotal Number ofRowsinch theTriangle.
- The title says it's better to have an O (n) space complexity, and to think that general motion rules may require O ( n 2 ) of the space, how can only use O (n), a little bit of brain turn to think that there is no need to save the path from the root to each node and Ah! We calculate to the first line only need to save the current line of the shortest path of each node, and before we do not care at all, so apply an array of n, each can overwrite the previous. But notice a small place, to update the path of each row, start from the right, or the shortest of the previous line will be overwritten.
classSolution { Public:intMinimumtotal ( vector<vector<int>>& Triangle) {intn = triangle.size ();if(n==0)return 0;if(n==1)returntriangle[0][0];intdp[n+1];intMin = Int_max; for(intI=0; i<n+1; i++) Dp[i]=int_max; dp[1] = triangle[0][0]; for(intI=1; i<n;i++) { for(intj=i+1;j>0; j--) {Dp[j]=min (dp[j-1],DP[J]) +triangle[i][j-1];if(i==n-1&&dp[j]<min) {Min = Dp[j]; } } }returnMin; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode" triangle to find the minimum and path