[leetcode] Triangle

Triangle

动态规划入门题

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        vector<vector<int>>::size_type length=triangle.size();//求行数
        if (length==0) {//triangle为空,返回0
            return 0;
        }
        for (int i=1; i<length; ++i) {//从第二行开始处理
            vector<int>::size_type length_column=triangle[i].size();//每一行中数的个数
            for (int j=0; j<length_column; ++j) {
                if (j==0) {//注意处理边界情况
                    triangle[i][j]=triangle[i][j]+triangle[i-1][j];
                }else if (j==length_column-1){
                    triangle[i][j]=triangle[i][j]+triangle[i-1][j-1];
                }else{
                    int left=triangle[i][j]+triangle[i-1][j-1];
                    int right=triangle[i][j]+triangle[i-1][j];
                    triangle[i][j]=left<right?left:right;
                }
            }
        }
        //比较最后一行的数
        int res=triangle[length-1][0];
        for (int k=0; k<triangle[length-1].size();++k) {
            res=res<triangle[length-1][k]?res:triangle[length-1][k];
        }
        
        return res;
    }
};


class Solution {
public:
    //定义状态为从起点--当前位置的最小路径和
    int minimumTotal(vector<vector<int> > &triangle) {
        if(triangle.size()==0){
            return 0;
        }
        for(int i=1;i<triangle.size();++i){//状态转移(*从第二行开始处理*)
            for(int j=0;j<triangle[i].size();++j){
                if(j==0){
                    triangle[i][j]=triangle[i-1][j]+triangle[i][j];
                }else if(j==triangle[i].size()-1){
                    triangle[i][j]=triangle[i-1][j-1]+triangle[i][j];
                }else{
                    triangle[i][j]=triangle[i][j]+min(triangle[i-1][j],triangle[i-1][j-1]);
                }
            }
        }
        int res=triangle[triangle.size()-1][0];//结果
        for(int k=0;k<triangle[triangle.size()-1].size();++k){
            res=min(res,triangle[triangle.size()-1][k]);
        }
        return res;
    }
};


class Solution {
public:
    //定义状态为当前节点--终点的最短路径和(自底向上)
    int minimumTotal(vector<vector<int> > &triangle) {
        if(triangle.size()==0){
            return 0;
        }
        for(int i=triangle.size()-2;i>=0;--i){//状态转移(从倒数第二行开始)
            for(int j=0;j<triangle[i].size();++j){
                triangle[i][j]=triangle[i][j]+min(triangle[i+1][j],triangle[i+1][j+1]);
            }
        }
        return triangle[0][0];
    }
};



参考 leetcode之Triangle

你可能感兴趣的:([leetcode] Triangle)