120. Triangle
可以用一个数组就能解决,思路一样的懒得写了,刚开始以为左中右都能走,结果是只能走右和中,因为我把三角化成矩阵的时候想错了,走的路径是针对三角的
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { if (triangle.empty())return 0; int n = triangle.size(); vector<vector<int>> path(n, vector<int>(n, 0)); path[0][0] = triangle[0][0]; for (int i = 1;i < n;i++) { for (int j = 0;j < triangle[i].size();j++) { if (j == 0)path[i][j] = path[i-1][j] + triangle[i][j]; else if (j == i)path[i][j] = path[i - 1][j - 1] + triangle[i][j]; else path[i][j] = min(path[i - 1][j] + triangle[i][j], path[i - 1][j - 1] + triangle[i][j]); } } int res = path[n - 1][0]; for (int i = 0; i < triangle[n - 1].size(); ++i) { res = min(res, path[n - 1][i]); } return res; } };
Runtime: 4 ms, faster than 99.61% of C++ online submissions for Triangle.