【Jump Game】cpp
题目:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
代码:
class Solution { public: bool canJump(vector<int>& nums) { return Solution::dfs(nums, 0); } static bool dfs(vector<int>& nums, int index) { if ( index>=nums.size()-1 ) return true; if ( nums[index]==0 ) return false; for ( int i = nums[index] ; i >= 1; --i ) { if ( Solution::dfs(nums, index+i) ) return true; } return false; } };
tips:
随手写了一个DFS Solution,结果是对的但是超时,shit...
====================================
由于不会Greedy的算法,一心想写一个dp solution,结果最后dp没写成,写成了个greedy;不过代码还是很简洁和高效的:
class Solution { public: bool canJump(vector<int>& nums) { int max_jump = 0; max_jump = std::max(max_jump, nums[0]); for ( int i = 0; i<=max_jump; ++i ) { if ( max_jump>=nums.size()-1 ) return true; max_jump = std::max(max_jump, i+nums[i]); } return false; } };
tips:
算法的时间复杂度O(n),空间复杂度O(1)。
正常往后迭代变量,每次迭代变量后,维护一个max_jump(即走到元素i,已知可以走到最远的元素下标)。
如果下标大于等于nums.size()-1,则返回true;如果遍历到max_jump了,且没有到达nums.size()-1,则返回false。
后来想想能不能用dp或者dfs再解一次,但想来想去,dp或者dfs解法的核心无非还是变形的greedy,没有太大意思。完毕。
===============================================
第二次过这道题,直接写了greedy的AC了。
class Solution { public: bool canJump(vector<int>& nums) { if ( nums.size()==0 ) return false; int maxLength = 0; for ( int i=0; i<=maxLength; ++i ) { if ( i+nums[i]>maxLength ) { maxLength = i+nums[i]; } if ( maxLength>=nums.size()-1 ) return true; } return maxLength>=nums.size()-1; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?