Monday, November 25, 2013

LeetCode Problem : Triangle

Problem


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.

Code


int minimumTotal(vector<vector<int> > &triangle) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int n = triangle.size();
    if(n == 1)
        return triangle[0][0];
    vector<vector<int> > M(n - 1);
    M[0].push_back(triangle[0][0]);
    for(int i = 1; i < n - 1;++i){
        M[i].push_back(M[i - 1][0] + triangle[i][0]);
        for(int j = 1; j < i;++j){
            M[i].push_back(min(M[i - 1][j - 1],M[i - 1][j]) + triangle[i][j]);
        }
        M[i].push_back(M[i - 1][i - 1] + triangle[i][i]);
    }
    int sum = M[n - 2][0] + triangle[n - 1][0];
    for(int j = 1; j < n - 1;++j){
    int num = min(M[n - 2][j - 1],M[n - 2][j]) + triangle[n - 1][j];
    if(sum > num)
        sum = num;
    }
    int num = M[n - 2][n - 2] + triangle[n - 1][n - 1];
    if(sum > num)
        sum = num;
    return sum;
}

No comments:

Post a Comment