zoukankan      html  css  js  c++  java
  • 120. Triangle 以及一个多维vector如何初始化

    1.刚开始result的初始化写的是vector<vector<int>> result,然后再去对result[0][0] = triangle[0][0]赋值,一直报错。老问题了!

    2.多维vector的初始化:

    vector<vector<int>> result(height,vector<int>(width))

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

     简化版

    class Solution {
    public:
        int minimumTotal(vector<vector<int>>& triangle) {
            int length = triangle.size();
            vector<vector<int>> result(length,vector<int>(length));
            result[0][0] = triangle[0][0];
            for(int i = 1;i < length;i++){
                for(int j = 0;j <= i;j++){
                    if(j == 0)
                        result[i][j] = result[i-1][j] + triangle[i][j];
                    else if(j == i)
                        result[i][j] = result[i-1][j-1] + triangle[i][j];
                    else
                        result[i][j] = min(result[i-1][j],result[i-1][j-1]) + triangle[i][j];
                }
            }
            int min_num = 0x7FFFFFFF;
            for(int i = 0;i < length;i++){
                if(result[length-1][i] < min_num)
                    min_num = result[length-1][i];
            }
            return min_num;
        }
    };
  • 相关阅读:
    Oracle序列使用:建立、删除
    struts1.x入门
    SQL的四种连接-左外连接、右外连接、内连接、全连接
    eclipse更改文件编码方式
    使用links方式安装Eclipse插件
    JAVA:Eclipse代码自动提示
    MyEclipse注释配置
    全面理解SQL
    一秒去除Win7快捷方式箭头
    Eclipse快捷键大全(转载)
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/7467172.html
Copyright © 2011-2022 走看看