Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
解题过程:首先,定义一个gobal变量保存目前跳动最远的距离,用一个本地变量保存当前一步出发能跳的最远距离。利用动态规划思想,建立状态转移方程。这里面的状态就是走到每一步时的golbal值,状态转移方程:global[i] = max{nums[i]+i, global[i-1]}。
代码:
#include <iostream>
#include<vector>
using namespace std;
int maxA(int a,int b){
if(a>b){
return a;
}else{
return b;
}
}
int main()
{
vector<int> nums;
int s;
while(cin>>s){
nums.push_back(s);
}
int n = nums.size();
int reach = 0;
for(int i=0 ;i<n-1 && reach>=i;i++){
reach = maxA(nums[i]+i, reach); //状态转移方程
}
if(reach>=n-1){
cout << "true" << endl;
}else{
cout << "false" << endl;
}
return 0;
}

本文介绍了一个跳跃游戏的问题解决方法,通过动态规划思想确定能否从数组起始位置到达末尾。使用状态转移方程来更新最远可达位置,最终判断是否能够到达最后一个元素。
1028

被折叠的 条评论
为什么被折叠?



