LeetCode 55. 跳躍遊戲 ( 回溯 dp 貪心
這個題位元組一面做過 不過當時沒想到好的解法
首先能寫出一個回溯的搜尋演算法:
class Solution {
private boolean[] vis;
private boolean dfs(int[] nums,int cur){
if(cur==nums.length-1){
return true;
}
boolean rs=false;
vis[cur]=true;
for(int i=1;i<=nums[cur];i++){
// 向右/向左
// ? 指正,這裡是不需要向左跳的,不過即使如此也過不了qaq
if(cur+i<nums.length&&!vis[cur+i]){
vis[cur+i]=true;
rs=rs||dfs(nums,cur+i);
vis[cur+i]=false;
}
}
return rs;
}
public boolean canJump(int[] nums) {
vis=new boolean[nums.length];
return dfs(nums,0);
}
}
超時
突然想到這個題很適合用dp來做:
class Solution {
public boolean canJump(int[] nums) {
// dp[i]表示從第i個位置出發,能否到達終點
// 遞推公式:dp[i]=dp[i+1] || dp[i+2] || ... || dp[i+nums[i]]
boolean[] dp=new boolean[nums.length];
dp[dp.length-1]=true;
for(int i=dp.length-2;i>=0;i--){
// 從當前點,判斷所有他能到達的點,看能否到達
for(int j=1;j<=nums[i];j++){
if(dp[i+j]){
dp[i]=true;
break;
}
}
}
return dp[0];
}
}
雖然挺慢的
最妙的還是這個(,雖然不是不能馬上想到,這個題dp應該是能馬上想到的
class Solution {
public boolean canJump(int[] nums) {
// reach表示能通過跳躍到達的最遠位置
int reach=0;
for(int i=0;i<nums.length;i++){
if(i>reach){
// 當前遍歷到的位置,是不能通過跳躍到達的
// 那麼自然也到不了終點
return false;
}
reach=Math.max(reach,nums[i]+i);
}
// 上述迴圈走完,說明對於終點,也是可以通過跳躍到達
return true;
}
}
相關文章
- 貪心——55. 跳躍遊戲 && 45.跳躍遊戲II遊戲
- leetcode:跳躍遊戲II(java貪心演算法)LeetCode遊戲Java演算法
- 【LeetCode】55. 跳躍遊戲 (動態規劃)LeetCode遊戲動態規劃
- [Leetcode]44.跳躍遊戲Ⅰ&&45.跳躍遊戲ⅡLeetCode遊戲
- LeetCode 45. 跳躍遊戲 IILeetCode遊戲
- 32天【程式碼隨想錄演算法訓練營34期】第八章 貪心演算法 part02 (● 122.買賣股票的最佳時機II ● 55. 跳躍遊戲 ● 45.跳躍遊戲II )演算法遊戲
- LeetCode 45跳躍遊戲&46全排列LeetCode遊戲
- 跳躍遊戲遊戲
- 程式碼隨想錄演算法訓練營day32 | leetcode 122. 買賣股票的最佳時機 II、55. 跳躍遊戲、45. 跳躍遊戲 II演算法LeetCode遊戲
- Codeforces 459E Pashmak and Graph:dp + 貪心
- Leetcode 貪心:差值調整LeetCode
- HDU 4550卡片遊戲(貪心)遊戲
- 0055-跳躍遊戲遊戲
- hdu4313 貪心並查集 || 樹形dp並查集
- 跳躍遊戲精細化遊戲
- 「演算法思想」分治、動態規劃、回溯、貪心一鍋燉演算法動態規劃
- Codeforces 571B Minimization:dp + 貪心【前後相消】
- 程式碼隨想錄演算法訓練營第三十二天 | 122.買賣股票的最佳時機 55.跳躍遊戲 45.跳躍遊戲II演算法遊戲
- 55-jump Game 跳躍遊戲GAM遊戲
- Educational Codeforces Round 167 (Rated for Div. 2) D(dp,貪心)
- 列舉子集+預處理最佳化dp+貪心視角轉化成可做dp
- CF 1029E Tree with Small Distances 樹形DP or 貪心
- HDU 5135 Little Zu Chongzhi's Triangles(狀壓dp或者貪心)
- LeetCode:動態規劃+貪心題目整理LeetCode動態規劃
- leetcode1546題解【字首和+貪心】LeetCode
- 微信小遊戲之跳一跳-電腦自動跳躍遊戲
- 【LeetCode】貪心演算法–分發糖果(135)LeetCode演算法
- LeetCode解題記錄(貪心演算法)(二)LeetCode演算法
- LeetCode解題記錄(貪心演算法)(一)LeetCode演算法
- leetcode1552題解【二分+貪心】LeetCode
- 試著跳一下?講講遊戲中的“跳躍”遊戲
- 說說你對貪心演算法、回溯演算法的理解?應用場景?演算法
- leetcode - 1686 - 石子游戲 VI - 貪心 - 數學分析LeetCode
- 貪心模式記錄模式
- 貪心演算法演算法
- redis 跳躍表Redis
- 力扣 leetcode 435. 無重疊區間 貪心力扣LeetCode
- Least Cost Bracket Sequence(貪心)ASTRacket