【剑指Offer】动态规划(1)

36 篇文章 0 订阅

剑指 Offer 42. 连续子数组的最大和

输入: nums = [-2,1,-3,4,-1,2,1,-5,4]



• 1 <= arr.length <= 10^5
• -100 <= arr[i] <= 100
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = nums[0], cur = nums[0], n = nums.size();
for(int i = 1; i < n; ++ i){
if(cur < 0)cur = 0;
cur += nums[i];
ans = max(ans, cur);
}
return ans;
}
};


剑指 Offer 47. 礼物的最大价值

输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]



• 0 < grid.length <= 200
• 0 < grid[0].length <= 200
解法一：
class Solution {
public:
int maxValue(vector<vector<int>>& grid) {
queue<pair<int, int>> q;
q.push(pair<int, int>(0, 0));
int ans = -INT_MAX, n = grid.size(), m = grid[0].size();
int dirs[2][2] = {{0, 1}, {1, 0}}, pred[2][2] = {{-1, 0}, {0, -1}};
vector<vector<bool>> vis(n, vector<bool>(m));
vis[0][0] = true;
while(q.empty() == false){
auto p = q.front();
q.pop();
int x = p.first, y = p.second, best = grid[x][y];
ans = max(ans, best);
for(int i = 0; i < 2; ++ i){
int ox = x + pred[i][0], oy = y + pred[i][1];
int nx = x + dirs[i][0], ny = y + dirs[i][1];
if(ox >= 0 && ox < n && oy >= 0 && oy < m){
best = max(best, grid[x][y] + grid[ox][oy]);
}
if(nx >= 0 && nx < n && ny >= 0 && ny < m){
if(vis[nx][ny] == false){
q.push(pair<int, int>(nx, ny));
vis[nx][ny] = true;
}
}
}
grid[x][y] = best;
}
return grid[n - 1][m - 1];
}
};


	[1  3  1]						[     1     ]
[1  5  1]			=>			[   1   3   ]
[4  2  1]						[ 4   5   1 ]
[   2   1   ]
[     1     ]


解法二：
class Solution {
public:
int maxValue(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < n; ++ i){
for(int j = 0; j < m; ++ j){
if(i != 0 || j != 0){
if(i == 0){
grid[i][j] = grid[i][j] + grid[i][j - 1];
}else if(j == 0){
grid[i][j] = grid[i][j] + grid[i - 1][j];
}else grid[i][j] = max(grid[i][j - 1], grid[i - 1][j]) + grid[i][j];
}
}
}
return grid[n - 1][m - 1];
}
};


• 1
点赞
• 1
收藏
• 打赏
• 0
评论
08-04
10-31
12-15
12-10
08-13
01-27 1万+
02-26 1万+
02-02
11-08
07-30
03-27 457
03-31 2471

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

Ryu眼神不太好

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。