Triangle

Description

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

Notice
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.
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).

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
class Solution {
public:
    /**
     * @param triangle: a list of lists of integers.
     * @return: An integer, minimum path sum.
     */
    int minimumTotal(vector<vector<int> > &triangle) {
        // write your code here
        if (triangle.empty()) {
            return 0;
        }
        int level = triangle.size();
        // copy the last row
        vector<int> result = triangle[level-1];
        // begin from the second last row
        for (int i = level-2; i >= 0; --i) {
            for (int j = 0; j < triangle[i].size(); ++j) {
                // tmp min result = self + min(next row two children)
                // then put the tmp min reuslt in the result[0]
                // because the size of higher level will be "-1" , so the data will not be overlapping
                result[j] = triangle[i][j] + min(result[j], result[j+1]);
            }
        }
        return result[0];
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""