LeetCode120. 三角形最小路径和

//120. 三角形最小路径和
class Solution {
public:
  int minimumTotal(vector<vector<int>>& s) {
    if (s.empty()) return 0;
    int n = s.size();
    auto f(s);
    for (int i = 1; i < n; i++)
      for (int j = 0; j <= i; j++)
        if (j == 0) f[i][j] += f[i - 1][j];
        else if (j == i) f[i][j] += f[i - 1][j - 1];
        else f[i][j] += min(f[i - 1][j], f[i - 1][j - 1]);
    int ans = f.back().front();
    for (auto x : f.back())
      ans = min(ans, x);
    return ans;
  }
};
//优化空间,有点类似背包的空间优化
//不过还是建议先写出最简单的dp,然后在他的基础上进行优化,不然,很难想
class Solution {
public:
  int minimumTotal(vector<vector<int>>& s) {
    if (s.empty()) return 0;
    int n = s.size();
    vector<int> f(n, 0);
    for (int i = 0; i < n; i++)
      for (int j = i; j >= 0; j--)
        if (j == 0) f[j] += s[i][j];
        else if (j == i) f[j] = f[j - 1] + s[i][j];
        else f[j] = min(f[j], f[j - 1]) + s[i][j];
    int ans = f.front();
    for (auto x : f) ans = min(ans, x);
    return ans;
  }
};
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页