LeetCode | 120. 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>& triangle) {
        int row = triangle.size();
		if (row < 1)
			return 0;
		vector> dp(2, vector(row + 1, 0));

		dp[0][0] = triangle[0][0];
		for (int i = 1; i < row; i++)
		{
			for (int j = 0; j <= i; j++)
			{
				int val1 = 999999, val2 = 999999, val3 = 999999;
				if (j - 1 >= 0)
					val1 = dp[(i - 1) % 2][j - 1];
				/*if (j + 1 < i)
					val3 = dp[(i - 1) % 2][j + 1];*/
				if(j < i)
					val2 = dp[(i - 1) % 2][j];
				dp[i % 2][j] = min(min(val1, val2), val3) + triangle[i][j];
			}
		}
		int minimal = dp[(row - 1) % 2][0];
		for (int i = 1; i < row; i++)
			minimal = min(minimal, dp[(row - 1) % 2][i]);
		return minimal;
    }
};

 

性能优于95+%~

 

你可能感兴趣的:(LeetCode,leetcode,C++)