LeetCode 55 Jump Game
題目如下:
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.
看到題之後第一個想法就是判斷每個位置 (i) 能否加上最大跳躍距離(A[i])到達n-1(陣列長度減1),,,如果不行的話再遍歷i+( 1~A[i] )這些位置,然後遞迴下去判斷,,
下面是程式碼:
class Solution {
public:
int c[100000]={0};
bool canJump(vector<int>& nums) {
return sss(nums, 0);
}
bool sss(vector<int>& nums, int cur){
c[cur] = 1;
if(cur + nums[cur] >= nums.size()-1) return true;
if(cur == nums.size()-1) return true;
if(nums[cur] == 0) return false;
for(int i = nums[cur]; i>=1;i--){
if(c[cur+i] == 1) continue;
if(sss(nums, cur+i)) return true;
}
return false;
}
};
用了個大陣列儲存已跑過的位置,,,不然最後一個test就TLE了,,,
不出意外效率極低,,,
然後發現其實不需要遞迴,只要從位置0開始判斷所能達到的最遠距離是否大於等於n-1。
遍歷的時候要注意更新最大距離,並且要注意當前的位置i是否可以達到,即小於等於記錄的最大距離。
附上程式碼~
bool canJump(vector<int>& nums) {
if(nums.size() == 1) return true;
int max=0;
for(int i = 0; i < nums.size();i++){
if(i > max) return false;
if(i + nums[i] >= nums.size()-1) return true;
max = i+nums[i] > max?i+nums[i]:max;
}
return false;
}
效率果然好多了。。。
時間是少了很多,,但可以看出還是趕不上大部分人的水平,還得多多交流參考QwQ
相關文章
- [LeetCode] 55. Jump GameLeetCodeGAM
- 55-jump Game 跳躍遊戲GAM遊戲
- Leetcode jump GameLeetCodeGAM
- [LeetCode] Jump Game IILeetCodeGAM
- Leetcode jump Game IILeetCodeGAM
- Leetcode-Jump GameLeetCodeGAM
- Jump Game leetcode javaGAMLeetCodeJava
- Leetcode-Jump Game IILeetCodeGAM
- Jump Game II leetcode javaGAMLeetCodeJava
- [LeetCode] 45. Jump Game IILeetCodeGAM
- Jump Game(C++)GAMC++
- 【Leetcode】1340. Jump Game V 【動態規劃/記憶性搜尋】LeetCodeGAM動態規劃
- 【leetcode】45. Jump Game II 非負陣列的最少跳躍步數LeetCodeGAM陣列
- LeetCode:Game of LifeLeetCodeGAM
- LeetCode-Game of LifeLeetCodeGAM
- LeetCode-Nim GameLeetCodeGAM
- Leetcode 292. Nim GameLeetCodeGAM
- LeetCode-Design Snake GameLeetCodeGAM
- 【Leetcode】1690. Stone Game VIILeetCodeGAM
- 292. Nim Game--LeetCode RecordGAMLeetCode
- LeetCode 403 Frog Jump 青蛙過河 Javascirpt 解決方案LeetCodeJava
- leetcode 679. 24 Game(遊戲24點)LeetCodeGAM遊戲
- 【LeetCode】55. 跳躍遊戲 (動態規劃)LeetCode遊戲動態規劃
- LeetCode 55. 跳躍遊戲 ( 回溯 dp 貪心LeetCode遊戲
- 55
- java GameJavaGAM
- Wooden GameGAM
- Card GameGAM
- Shop GameGAM
- CF1768F Wonderful Jump 題解
- Fast Car GameASTGAM
- Infinite Card GameGAM
- game development -- flowGAMdev
- 《JUMP》中最強的好女人角色排行TOP 10
- Lesson 55 - Not a gold mineGo
- Flip Game(POJ 1753)GAM
- E. Wooden GameGAM
- C. Game on PermutationGAM