码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 120

时间:2019-02-08 11:53:43      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:triangle   etc   ret   for   int   code   min   tor   find   

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if(triangle.size() == 1) return triangle[0][0];
        triangle[1][0] += triangle[0][0];triangle[1][1] += triangle[0][0];
        if(triangle.size() == 2) return min(triangle[1][0],triangle[1][1]);
        int a = min(triangle[1][0],triangle[1][1]);
        for(int i=0;i < 2;i++){
            triangle[2][i] += a;
        }
        triangle[2][2] += triangle[1][1];
        for(int i=3;i < triangle.size();i++){
            triangle[i][0] += min(triangle[i-1][0],triangle[i-1][1]);
            for(int j=1;j < triangle[i].size()-2;j++){
                int x = min(triangle[i-1][j-1],triangle[i-1][j]);
                int y = min(x,triangle[i-1][j+1]);
                triangle[i][j] += y;
            }
            triangle[i][triangle[i].size()-2] += min(triangle[i-1][triangle[i].size()-2],triangle[i-1][triangle[i].size()-3]);
            triangle[i][triangle[i].size()-1] += triangle[i-1][triangle[i].size()-2];
        }
        return findmin(triangle[triangle.size()-1]);
    }
    int findmin(vector<int> temp){
        int minnum = temp[0];
        for(int i=1;i < temp.size();i++){
            if(minnum > temp[i]) minnum = temp[i];
        }
        return minnum;
    }
};

——题意没写清楚,相邻是左中右还是中右,WA了一发

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

_

Leetcode 120

标签:triangle   etc   ret   for   int   code   min   tor   find   

原文地址:https://www.cnblogs.com/cunyusup/p/10355954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!