120. 三角形最小路径和

dfs递归, 超时

class Solution {
public:
    int ans;
    void dfs(vector<vector<int>>& triangle, int x, int y, int sum){
        if(x==triangle.size()-1){
            ans = min(sum,ans);
            return;
        }
        dfs(triangle, x+1, y, sum+triangle[x+1][y]);
        if(y+1<triangle[x+1].size())
            dfs(triangle, x+1, y+1, sum+triangle[x+1][y+1]);
    }
    int minimumTotal(vector<vector<int>>& triangle) {
        ans = INT32_MAX;
        dfs(triangle,0,0,triangle[0][0]);
        return ans;
    }
};

动态规划,上一行lastdp, 辅助计算curdp

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

自底向上,动态规划

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

你可能感兴趣的:(LeetCode,算法,数据结构)