File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def canJump (self , nums : List [int ]) -> bool :
3
+ # Recursive Solution
4
+ # Time: O(Max(nums) ^ n)
5
+ # Space: O(n)
6
+ n = len (nums )
7
+
8
+ def can_reach (i ):
9
+ if i == n - 1 :
10
+ return True
11
+
12
+ for jump in range (1 , nums [i ]+ 1 ):
13
+ if can_reach (i + jump ):
14
+ return True
15
+
16
+ return False
17
+
18
+ return can_reach (0 )
19
+
20
+
21
+ class Solution :
22
+ def canJump (self , nums : List [int ]) -> bool :
23
+ # Top Down DP (Memoization)
24
+ # Time: O(n^2)
25
+ # Space: O(n)
26
+ n = len (nums )
27
+ memo = {n - 1 : True }
28
+
29
+ def can_reach (i ):
30
+ if i in memo :
31
+ return memo [i ]
32
+
33
+ for jump in range (1 , nums [i ]+ 1 ):
34
+ if can_reach (i + jump ):
35
+ memo [i ] = True
36
+ return True
37
+
38
+ memo [i ] = False
39
+ return False
40
+
41
+ return can_reach (0 )
42
+
43
+
44
+ class Solution :
45
+ def canJump (self , nums : List [int ]) -> bool :
46
+ # Greedy - Start at end
47
+ # Time: O(n)
48
+ # Space: O(1)
49
+ n = len (nums )
50
+ target = n - 1
51
+
52
+ for i in range (n - 1 , - 1 , - 1 ):
53
+ max_jump = nums [i ]
54
+ if i + max_jump >= target :
55
+ target = i
56
+
57
+ return target == 0
You can’t perform that action at this time.
0 commit comments