-
Notifications
You must be signed in to change notification settings - Fork 0
/
jump_game.cpp
106 lines (92 loc) · 2.01 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// 55. Jump Game: https://leetcode.com/problems/jump-game
// Author: [email protected]
#include <stdio.h>
#include <algorithm>
#include <vector>
// Backtracking, time limit exceeded
class Solution1
{
public:
bool canJump(std::vector<int>& nums)
{
return canJump(nums, 0);
}
private:
bool canJump(std::vector<int>& nums, int start)
{
if (start >= nums.size() - 1)
{
return true;
}
int end = start + nums[start];
for (int i = end; i > start; i--)
{
if (canJump(nums, i))
{
return true;
}
}
return false;
}
};
// Dynamic programming
class Solution2
{
public:
enum JumpState
{
kBad,
kGood,
};
bool canJump(std::vector<int>& nums)
{
if (nums.size() == 0)
{
return true;
}
std::vector<JumpState> states(nums.size(), kBad);
states[nums.size() - 1] = kGood;
for (int i = nums.size() - 2; i >= 0; i--)
{
int end = std::min(nums[i] + i, (int)(nums.size() - 1));
for (int j = i + 1; j <= end; j++)
{
if (states[j] == kGood)
{
states[i] = kGood;
break;
}
}
}
return (states[0] == kGood);
}
};
// Greedy
class Solution3
{
public:
bool canJump(std::vector<int>& nums)
{
if (nums.size() == 0)
{
return true;
}
int last_idx = nums.size() - 1;
for (int i = nums.size() - 1; i >= 0; i--)
{
if (nums[i] + i >= last_idx)
{
last_idx = i;
}
}
return (last_idx == 0);
}
};
using Solution = Solution3;
int main(int argc, char* argv[])
{
std::vector<int> nums = {3, 2, 1, 0, 4};
bool is_jump = Solution().canJump(nums);
printf("Can jump? %s\n", (is_jump ? "Yes" : "No"));
return 0;
}