Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cherry-pickup.cpp 1.57 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-12-04 02:18 +08:00 . Update cherry-pickup.cpp
// Time: O(n^3)
// Space: O(n^2)
class Solution {
public:
int cherryPickup(vector<vector<int>>& grid) {
// dp holds the max # of cherries two k-length paths can pickup.
// The two k-length paths arrive at (i, k - i) and (j, k - j),
// respectively.
const int n = grid.size();
vector<vector<int>> dp(n, vector<int>(n, -1));
dp[0][0] = grid[0][0];
const int max_len = 2 * (n - 1);
for (int k = 1; k <= max_len; ++k) {
for (int i = min(k, n - 1); i >= max(0, k - n + 1); --i) { // 0 <= i < n, 0 <= k-i < n
for (int j = min(k , n - 1); j >= i; --j) { // i <= j < n, 0 <= k-j < n
if (grid[i][k - i] == -1 ||
grid[j][k - j] == -1) {
dp[i][j] = -1;
continue;
}
int cnt = grid[i][k - i] + ((i == j) ? 0 : grid[j][k - j]);
int max_cnt = -1;
static const vector<pair<int, int>> directions{{0, 0}, {-1, 0}, {0, -1}, {-1, -1}};
for (const auto& direction : directions) {
const auto ii = i + direction.first;
const auto jj = j + direction.second;
if (ii >= 0 && jj >= 0 && dp[ii][jj] >= 0) {
max_cnt = max(max_cnt, dp[ii][jj] + cnt);
}
}
dp[i][j] = max_cnt;
}
}
}
return max(dp[n - 1][n - 1], 0);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助