Tuesday, March 12, 2013

Triangle

/*
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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int rowSize = triangle.size();
 if(rowSize==0) return 0;
 int const bigValue = 200;
 int lineMin = bigValue;
 int j;
 for(int i=0; i<rowSize; i++){
  if(triangle[i].size()!=(i+1)) return 0;
  if(i>0){
   for(j=0; j<(i+1); j++){
    lineMin = bigValue;
    if(j<triangle[i-1].size())
    lineMin = min(triangle[i-1][j] + triangle[i][j], lineMin);
    if(j>=1){
     lineMin = min(triangle[i-1][j-1] + triangle[i][j], lineMin);
    }
    triangle[i][j] = lineMin;
   }
  }
 }
         lineMin = bigValue;
 for(j=0; j<triangle[rowSize-1].size(); j++){
  lineMin = min(lineMin, triangle[rowSize-1][j]);
 }
 return lineMin;
    }
};

No comments:

Post a Comment