-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJump Game.cpp
79 lines (59 loc) · 1.56 KB
/
Jump Game.cpp
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
/*class Solution {
public:
bool canJump(vector<int>& nums) {
int length = nums.size();
return reach(nums, 0, length - 1);
}
bool reach(vector<int>&nums, int index, int distance){
int max_step = nums[index];
if(max_step >= distance)
return true;
for(int i = 1; i <= max_step; i++){
if(reach(nums, index+i, distance - i) == true)
return true;
}
return false;
}
};
// Naive Solution : Timee Limit Exceed
*/
// Dynamic Programing Solution
/*class Solution {
public:
bool canJump(vector<int>& nums) {
int length = nums.size();
bool* reach = new bool[length];
for(int i = 0; i < length; i++){
reach[i] = false;
}
for(int i = length - 1; i >= 0; i--){
if(nums[i] >= length - i -1){
reach[i] = true;
continue;
}
for(int j = 1; j <= nums[i]; j++){
if(reach[i+j] == true){
reach[i] = true;
break;
}
}
}
return reach[0];
}
};*/
//Optimized DP Solution
class Solution {
public:
bool canJump(vector<int>& nums) {
int length = nums.size();
int i = 0;
int max_reach = 0;
while(i <= max_reach && i < length){
int reach = nums[i] + i;
if(reach > max_reach) max_reach = reach;
if(max_reach >= length - 1) return true;
i++;
}
return false;
}
};