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; } };