Created
January 14, 2020 21:26
-
-
Save adamkorg/f0e1ab8394dede0fd36ce6267e56bd96 to your computer and use it in GitHub Desktop.
Leetcode 55: Jump Game (recursive+memo)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
// This recursive leetcode 55 solution times out on some the leetcode test cases | |
bool walk(const vector<int>& nums, int idx, vector<bool>& dp) { | |
if (idx == nums.size()-1) return true; | |
if (dp[idx]) return false; | |
int i = idx + nums[idx]; //start from biggest step | |
if (i >= nums.size()) i = nums.size()-1; //truncate if past end | |
for ( ; i > idx; --i) { | |
if (walk(nums, i, dp)) return true; | |
} | |
dp[idx] = true; | |
return false; | |
} | |
bool canJump(vector<int>& nums) { | |
vector<bool> dp(nums.size(), false); | |
return walk(nums, 0, dp); | |
} | |
int main() { | |
vector<int> nums {2,3,1,1,0}; //{3,2,1,0,4}; //{2,3,1,1,0}; //{2,3,1,1,4}; | |
cout << canJump(nums) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment