动态规划:青蛙跳石头 <--- 最后一步法

【问题来源】
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
*/


【参考文献】
https://www.bilibili.com/video/BV1xb411e7ww

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值