Thursday, March 10, 2016

LeetCode Q120: 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).
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.


class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<int> sum(triangle.size(), 0);
vector<int> tmpsum(triangle.size(), 0);
for(int i=0; i<triangle.size(); i++){
int nodeNum=i+1;
vector<int> layer=triangle[i];
for(int j=0; j<nodeNum; j++){
int n0=max(j-1, 0);
int n1=min(j, nodeNum-2);
tmpsum[j]=min(sum[n0]+layer[j], sum[n1]+layer[j]);
}
sum=tmpsum;
}
int min=INT_MAX;
for(int i=0; i<triangle.size(); i++)
min=sum[i]<min? sum[i]:min;
return min;
}
};


Round 2 solution:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty())
return 0;
vector<int> pre(triangle.size()+1, 0);
vector<int> cur(triangle.size()+1, 0);
int minv=INT_MAX;
for(int i=1; i<=triangle.size(); i++){
minv=INT_MAX;
for(int j=1; j<=i; j++){
int k = j==i? 1:0;
cur[j] = min(pre[j-1]+triangle[i-1][j-1], pre[j-k]+triangle[i-1][j-1]);
minv = min(minv, cur[j]);
}
cur[0]=cur[1];
pre = cur;
}
return minv;
}
};
view raw Q120Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment