【问题来源】
https://leetcode.com/problems/jump-game/
【问题描述】
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.
For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], return false.
【动态规划问题分析思路】
此问题是“存在型”问题,适用于利用动态规划方法解决。步骤如下:
1.确定状态
■ 研究最优策略的最后一步
■ 化为子问题
■ 注意:状态在动态规划中的作用属于定海神针
2.状态转移方程
■ 根据子问题定义直接得到
3.初始条件和边界情况
■ 细心,考虑周全
■ 注意:不能通过状态转移方程计算出的值设为初始条件
4.计算顺序
■ 原则是利用之前的计算结果。故可依据状态转移方程确定计算顺序。
上述分析思路详见:https://www.bilibili.com/video/BV1xb411e7ww
【算法代码】
#include <bits/stdc++.h>
using namespace std;
bool canJump(vector<int> &a) {
int n=a.size();
bool f[n];
f[0]=true;
for(int j=1; j<n; j++) {
f[j]=false;
for(int i=0; i<j; i++) {
if(f[i]&&i+a[i]>=j) {
f[j]=true;
break;
}
}
}
return f[n-1];
}
int main() {
vector<int> x;
int n;
while(cin>>n){
x.push_back(n);
}
cout<<canJump(x);
return 0;
}
/* LeetCode 55: Jump Game
in:2 3 1 1 4
out:true
in:3 2 1 0 4
out:false
*/