-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path55. Jump Game
More file actions
97 lines (56 loc) · 1.55 KB
/
55. Jump Game
File metadata and controls
97 lines (56 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// TLE
class Solution {
public:
bool canJump(vector<int>& nums, int idx){
if(idx>=nums.size()-1)
return true;
int maxSteps = nums[idx];
for(int i=1;i<=maxSteps;i++){
if(canJump(nums,idx+i))
return true;
}
return false;
}
bool canJump(vector<int>& nums) {
return canJump(nums,0);
}
};
MEMO
// TLE
class Solution {
public:
bool canJump(vector<int>& nums, int idx,vector<bool> &dp){
if(idx>=nums.size()-1)
return true;
if(dp[idx]==true)
return dp[idx];
int maxSteps = nums[idx];
for(int i=1;i<=maxSteps;i++){
if(canJump(nums,idx+i,dp))
return dp[idx] = true;
}
return dp[idx]=false;
}
bool canJump(vector<int>& nums) {
vector<bool> dp(nums.size());
return canJump(nums,0,dp);
}
};
GREEDY
class Solution {
public:
bool canJump(vector<int>& nums) {
int minJumps=0;
for(int i=nums.size()-2;i>=0;i--){
minJumps++;
//here we should not return, because
//we may come across some big number in the front, so tht we may not need to jump on this step
// if(nums[i]<minJumps)
// return false;
// also if we know with the prev number we r able to land on last idx, then we just need to check how we can reach the curr idx, not to end
if(nums[i]>=minJumps)
minJumps=0;
}
return minJumps==0;
}
};