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; } };
时间: 2024-11-08 22:46:19