[Leetcode] 741. Cherry Pickup 解题报告

LeetCode刷题:741. Cherry Pickup —摘樱桃 动态规划 LeetCode刷题:741. Cherry Pickup —摘樱桃 动态规划 原题链接:https://leetcode.com/problems/cherry-pickup/ In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the... 阅读详情

题目:

In a N x N grid representing a field of cherries, each cell is one of three possible integers.

  • 0 means the cell is empty, so you can pass through;
  • 1 means the cell contains a cherry, that you can pick up and pass through;
  • -1 means the cell contains a thorn that blocks your way.

    Your task is to collect maximum number of cherries possible by following the rules below:

  • Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells with value 0 or 1);
  • After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;
  • When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);
  • If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.

    Example 1:

    Input: grid =
    [[0, 1, -1],
     [1, 0, -1],
     [1, 1,  1]]
    Output: 5
    Explanation: 
    The player started at (0, 0) and went down, down, right right to reach (2, 2).
    4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
    Then, the player went left, up, up, left to return home, picking up one more cherry.
    The total number of cherries picked up is 5, and this is the maximum possible.
    

    Note:

  • grid is an N by N 2D array, with 1 <= N <= 50.
  • Each grid[i][j] is an integer in the set {-1, 0, 1}.
  • It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1.

    思路:

    我们定义dp[i][j]表示从(0, 0)开始的两条长为k的路径上,可以摘到的草莓的最大个数。而这两条长为k的路径的最终点为(i, k - i)和(j, k - j)。然后我们分别计算两条路径上可以摘到的草莓数。后面的没怎么看懂了。。。等到完全理解了思路再补充吧。。。

    代码:

    class Solution {
    public:
        int cherryPickup(vector<vector<int>>& grid) {
            int n = grid.size();
            /* dp holds maximum # of cherries two k-length paths can pickup. 
            The two k-length paths arrive at (i, k - i) and (j, k - j), respectively. */
            vector<vector<int>> dp(n, vector<int>(n, -1));
            dp[0][0] = grid[0][0];              // length k = 0
            const int maxK = 2 * (n - 1);       // maxK: number of steps from (0, 0) to (n-1, n-1).
            for (int k = 1; k <= maxK; ++k) {   // for every length k
                vector<vector<int>> curr(n, vector<int>(n, -1));
                // one path of length k arrive at (i, k - i)
                for (int i = 0; i < n && i <= k; ++i) {
                    if ( k - i >= n) {
                        continue;
                    }
                    // another path of length k arrive at (j, k - j)
                    for (int j = 0; j < n && j <= k; ++j) {
                        if (k - j >= n) {
                            continue;
                        }
                        if (grid[i][k - i] < 0 || grid[j][k - j] < 0) {     // keep away from thorns
                            continue;
                        }
                        int cherries = dp[i][j];    // # of cherries picked up by the two (k-1)-length paths.
                        if (i > 0) {
                            cherries = std::max(cherries, dp[i - 1][j]);
                        }
                        if (j > 0) {
                            cherries = std::max(cherries, dp[i][j - 1]);
                        }
                        if (i > 0 && j > 0) {
                            cherries = std::max(cherries, dp[i - 1][j - 1]);
                        }
                        // No viable way to arrive at (i, k - i)-(j, k-j).
                        if (cherries < 0) {
                            continue;
                        }
                        // Pickup cherries at (i, k - i) and (j, k -j ) if i != j. Otherwise, pickup (i, k-i).
                        cherries += grid[i][k - i] + (i == j ? 0 : grid[j][k - j]);
                        curr[i][j] = cherries;
                    }
                }
                dp = std::move(curr); 
            }
            return std::max(dp[n-1][n-1], 0); 
        }
    };
企业级Windows 10镜像封装实战:从规划到部署的完整指南 系统部署与镜像封装是企业IT运维中的核心基础技术,其原理在于通过创建预配置的系统模板,实现大规模计算机环境的快速、标准化部署。这项技术的核心价值在于将重复性手动操作转化为自动化流程,显著提升运维效率,保障环境一致性,并强化安全基线管理。在实际应用场景中,它尤其适用于新设备批量初始化、系统恢复和标准化环境构建。本文聚焦于Windows 10镜像的封装实践,深入探讨了使用Sysprep进行系统通用化处理以及通过DISM工具捕获WIM格式镜像的具体方法,为企业IT人员提供从零构建标准化系统镜像的完整路径。 阅读详情

相关推荐

强化学习经典算法笔记(九):LSTM加持的PolicyGradient算法

强化学习经典算法笔记(九):LSTM加持的PolicyGradient算法 在上文《强化学习经典算法笔记(八):LSTM加持的A2C算法解决POMDP问题》的基础上,实现了LSTM+MLP的Policy Gradient算法。 实现过程如下: import argparse, math, os, sys import numpy as np import gym from gym import wrappers import matplotlib.pyplot as plt import torch fr

hhy_csdn的博客 5636

【Leetcode】741. Cherry Pickup

题目地址: https://leetcode.com/problems/cherry-pickup/ 给定一个正方形矩阵,里面的数都是000、111或者−1-1−1,111代表有樱桃,000代表空地,可以走过去,−1-1−1代表障碍物,不能走过去。现在要求从(0,0)(0,0)(0,0)出发,每次只能向右或者向下走,走到(n−1,n−1)(n-1,n-1)(n−1,n−1),沿途不可以走到障碍物上...

数学、算法爱好者的博客 424

机器视觉中的特征提取【0】:什么是特征提取,特征提取有什么作用?

1.什么是特征提取? 特征提取的英文叫做feature extractor,它是将一些原始的输入的数据维度减少或者将原始的特征进行重新组合以便于后续的使用。简单来说有两个作用:减少数据维度,整理已有的数据特征。 这里我给一个例子来解释特征提取的第二个作用。那就是我们很熟悉的奖学金评定,我们知道学生的文化课成绩,道德分数,以及各种其他竞赛的成绩。摆在奖学金评定委员会面前的任务就是如何知道一个学生是否...

月下花弄影 5万+

741. 摘樱桃

一个N x N的网格(grid)代表了一块樱桃地,每个格子由以下三种数字的一种来表示: 0 表示这个格子是空的,所以你可以穿过它。 1 表示这个格子里装着一个樱桃,你可以摘到樱桃然后穿过它。 -1 表示这个格子里有荆棘,挡着你的路。 你的任务是在遵守下列规则的情况下,尽可能的摘到最多樱桃: 从位置(0, 0) 出发,最后到达 (N-1, N-1) ,只能向下或向右走,并且只能穿越有效的...

Umbrella Corporation 7404

VMware Workstation 不可恢复错误:(vcpu-1) Exception 0xc0000005 解决方案

1、错误信息如下:VMware Workstation 不可恢复错误:(vcpu-1) Exception 0xc0000005(access violation) hasoccurred.2、错误截图如下:3、错误原因分析:Exception 0xc0000005是访问冲突错误,通常指程序试图访问它没有权限的内存地址。在虚拟机环境中,这可能由多种因素引起,例如虚拟机配置错误、宿主机资源冲突、VMware软件问题或系统文件损坏。

m0_65065082的博客 4368

F280049C Crossbar X-BAR

X-BAR不是一个功能模块,只起内部外设与外设之间,或内部外设与GPIO的连接作用。配置X-BAR的就是在配置信号之间的连接。确实如这一节的开头所言,X-BAR提供了以各种配置连接设备输入、输出和内部资源的灵活性。学完这一节也知道为什么crossbar(X-BAR)的中文翻译是交叉开关。

xht2403267701的博客 3048

LeetCode 每日一题 ---- 【741.摘樱桃】

f[k][x1][x2]的最终结果是上述四种情况的最大值,然后再累加上grid[x1][k-x1]和grid[x2][k-x2]就可以得到最终该位置的答案。A往下,B往右:f[k][x1][x2] = f[k-1][x1-2][x2]A往右,B往下:f[k][x1][x2] = f[k-1][x1][x2-1]都往下:f[k][x1][x2] = f[k-1][x1-1][x2-1]都往右:f[k][x1][x2] = f[k-1][x1][x2]定义状态:f[k][x1][x2]

是微风,是晚霞,是无可替代 843

Unity 机械臂控制(二)——从碰撞检测到姿态解算:实现精准抓取

本文详细介绍了Unity中机械臂控制的实现方法,从碰撞检测到姿态解算,涵盖精准抓取的全流程。重点讲解了碰撞检测的分层处理、状态机设计、逆向运动学(IK)算法以及抓取稳定性优化等关键技术,并提供了实用的调试技巧和性能优化建议,帮助开发者实现高效的机械臂控制。

weixin_28693447的博客 304

LeetCode 741. 摘樱桃(动态规划)

【代码】LeetCode 741. 摘樱桃(动态规划)

记录一些刷过的题并分享学习心得 569

推荐系统:NDCG评价指标及其Python实现方法

除了推荐任务,在二分类任务中,也可以计算该指标,代码如下: # ndcg def get_dcg(y_pred, y_true, k): #注意y_pred与y_true必须是一一对应的,并且y_pred越大越接近label=1(用相关性的说法就是,与label=1越相关) df = pd.DataFrame({"y_pred":y_pred, "y_true":y_true}) ...

lanyuelvyun的博客 8241

Java后端中的链路追踪:使用OpenTelemetry实现全链路监控

在现代的微服务架构中,链路追踪是监控和优化系统性能的关键技术。通过链路追踪,我们可以跟踪请求在系统中的流转,识别性能瓶颈,定位问题根源。本文将介绍如何在Java后端应用中使用OpenTelemetry实现全链路监控,包括具体的实现步骤和代码示例。通过集成OpenTelemetry,您可以实现全面的链路追踪,帮助您识别瓶颈和潜在问题,从而提升系统的可靠性和用户体验。OpenTelemetry是一个开源项目,旨在提供统一的工具集来收集、处理和导出应用程序的遥测数据,包括跟踪、度量和日志。

聚娃科技开发者博客 1727

[leetcode]741摘樱桃,动态规划

题目表明去终点只能往下和往右,回去只能往上和往左,统计路程中经过的樱桃个数,那么就相当于从起点出发两次到终点,但两次路过到的同个樱桃就不能再重复计算,这两次不分先后,同时走深搜,然后用dp表示每个状态的最优解。 dp[x1][y1][x2]代表同时走两条路分别到(x1,y1)(x2,y2)的话,继续往下走所得到的最大值。因为是同时,他们两条路从起点开始移动的曼哈顿距离相等,dp有以下特点: 距离相等,就有x1+y1 == x2+y2,则y2=x1+y1-x2,所以可以用三维代表一个状态 遍历从起点开始,d

闭海通天的博客 624

cadence CIS 库建立--建立自己维护的CIS数据库

遇到一个问题,在使用cadecnce的时候,就是没有自己的本地/分享的数据库。 在画原理图或者PCB的时候,如果能搭建一个自己的数据库,在局域网或者本地 就好了。出于这样的想法,做了一些探索,找到了一种可能的答案。 由于数据库编制知识的缺乏,要自己建一个数据库似乎花费的时间会比较多。 偶发奇想,如果能够改编CIS 自带的数据库 另建立副本进行维护 就能够省下不少麻烦。 先说下CIS 是个啥。网上一搜:总之CIS 是个好东西。 功能强大。 点击CIS capture 中的 Options CIS Config

qq_29776365的博客 2万+

LeetCode //C - 741. Cherry Pickup

Abstract: This problem requires collecting the most cherries from the starting point (0,0) to the end point (n-1,n-1) in an n×n grid. The rules are: movement can only be to the right or down (outbound) and left or up (return), cannot pass through thorns (-

Made in Code 1113

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Cherry Pickup解题心得

Cherry Pickup解题心得 来源:https://leetcode.com/problems/cherry-pickup/description/ 题目复述输入一个n x n大小的地图,地图中的每个位置值包含三种值(-1, 0, 1),其中:-1:代表不允许通过 0:代表可以通过 1:代表可以通过,而且路上有个Cherry(樱桃)例如,输入: Input: grid = [[0, 1,

weixin_35816017的博客 781

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

【LeetCode 741】 Cherry Pickup

题目描述 In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you can...

iCode_girl的博客 736

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

LeetCode 741. Cherry Pickup

一、题目描述 In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you ...

AzureoSky的博客 364

Leetcode 741. Cherry Pickup dp

In a N x Ngridrepresenting a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you can pi...

salmonwilliam的博客 545

741. Cherry Pickup

741. Cherry Pickup方法1: dynamic programmingComplexity In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; ...

wilzxu的博客 210

LeetCode741. Cherry Pickup

https://leetcode.com/problems/cherry-pickup/description/ In a N x Ngridrepresenting a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can ...

dbvz4901的博客 192

LeetCode 741. Cherry Pickup(动态规划)

题目来源:https://leetcode.com/problems/cherry-pickup/ 问题描述 741.Cherry Pickup Hard In a N x Ngridrepresenting a field of cherries, each cell is one of three possible integers. 0 means the cell i...

da_kao_la的博客 429

leetcode 741. Cherry Pickup

In a N x Ngridrepresenting a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you can...

cmy203的博客 247

Leetcode 741 Cherry Pickup

http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/Problem:In a N x N grid representing a field of cherries, each cell is one of three possible integers.0 means the cell is ...

weixin_41826462的博客 369

【Leetcode】741. Cherry Pickup 741. 摘樱桃

解法 总而言之是DP的解法 把问题转换成有2个人从左上向右下走,一共能摘到的樱桃的最大数量 每个人都要走m+n-2步,走第t步时的状态可以表示为(t,r1,c1,r2,c2) 当然,这个五元组是冗余的,只需要三维就可以表示这个向量了,因为: t = r1+c1=r2+c2 在每个时刻,每个人都可以向下或向右,所以总共会产生4种情况: p1向下,p2向下:(t+1,r1+1,c1,r2+1,c...

lemonmillie的博客 502

Leetcode 741. Cherry Pickup DP

题意 一个n*n矩阵A,矩阵包含-1, 1, 0,其中-1不能通行,从矩阵左上角走到右下角,再走回左上角,第一次遇到1收益+1,第二次则不加,问你最大收益。 思路 这个题困扰我好久,网上题解包括discussion感觉都不是特别直观,现在终于完全想通了。。这里记录一下,希望能对大家有帮助。 这个题如果没有反复,那么显然可以用一个普通二维dp,直接求解 那么首先,我们想到的肯定是一个...

luke2834的专栏 2916

Leetcode:741. Cherry Pickup

c++code:class Solution { public: int cherryPickup(vector<vector<int>>& grid) { int n = grid.size(); int maxK = 2 * n - 1; int dp[maxK][n][n] = {-1}; memset(dp, -1, sizeof(dp)); for(

lyy_g的博客 740
上一篇: [Leetcode] 740. Delete and Earn 解题报告
下一篇: [Leetcode] 742. Closest Leaf in a Binary Tree
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值