Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created January 10, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/6bbd0487c0e29ec1d824d156e400cfc7 to your computer and use it in GitHub Desktop.
Save adamkorg/6bbd0487c0e29ec1d824d156e400cfc7 to your computer and use it in GitHub Desktop.
Leetcode 45: Jump Game II (iterative DP O(n^2) time)
//This is too slow for some of the leetcode test cases. Just posting for reference
#include <iostream>
#include <vector>
using namespace std;
int jump(vector<int>& nums) {
if (nums.size()==0) return 0;
vector<int> dp(nums.size(), -1);
int n = nums.size();
dp[0] = 0;
for (int i=1; i<n; ++i) { //calculate dp (minimum jumps) at each position
int minSteps = INT_MAX;
for (int j=0; j<i; ++j) { //calculate minSteps from each previous dp position
if (nums[j] < i-j) continue; //not possible to get to current from this previous
minSteps = min(minSteps, dp[j]+1);
}
dp[i] = minSteps;
}
return dp[n-1];
}
int main() {
vector<int> nums {2,3,0,1,4}; //{1,2,3}; //{2,3,1,1,4};
cout << jump(nums) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment