120. Triangle

image.png

image.png

top to down的方案
状态转移:

f(x,y) = min(f(x-1, y-1), f(x-1, y)) + triangle[x][y]
要注意边界条件的处理,j==0 (只能往上走);j==i 只能往斜上走

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

你可能感兴趣的:(120. Triangle)