120. Triangle

2018/05/15 leetcode 共 1168 字,约 4 分钟

title

link 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.

solution

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int n=triangle.size();
        vector<vector<int>> v(n,vector<int>(n,0));
        for(int i=0;i<n;i++) v[n-1][i]=triangle[n-1][i];
        for(int i=n-2;i>=0;i--){
            for(int j=0;j<=i;j++){
                v[i][j]=triangle[i][j]+min(v[i+1][j],v[i+1][j+1]);
                cout<<triangle[i][j]<<"  |  "<<v[i][j]<<"    ";

            }
            cout<<endl;
        }
        return v[0][0];
    }
};

其实可以o(n)的空间复杂度的,参考link

class Solution {
public:
	int minimumTotal(vector<vector<int>>& triangle) {
		int n = triangle.size();
		vector<int> dp(triangle.size(), 0);
		for (int i = 0; i < triangle[n-1].size(); i++) {
			dp[i] = triangle[n - 1][i];
		}
		for (int i = n - 2; i >= 0; i--) {
			for (int j = 0; j <= i;j++) {
				dp[j] = min(dp[j], dp[j + 1])+triangle[i][j];
				cout << dp[j] << " ";
			}
			cout << endl;
		}
		return dp[0];
	}
};

Search

    Table of Contents