leetcode之Jump Game

来源:互联网 发布:特效视频制作软件 编辑:程序博客网 时间:2024/06/05 22:30

原题如下:

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.

思路:还是动态规划问题,关键是要找出并理解状态转移方程,用一个变量保存前一个节点能够到达的最大步长,在计算当前能够到达的最大步长时,选取当前节点的最大步长与前一节点的最大步长中的较大值作为当前能够到达的最大步长(因为前一节点计算所得的最大步长一定能够到达下一个节点,否则到不了最后一个节点)。找出状态转移方程后编码就比较容易了。

class Solution {public:    bool canJump(int A[], int n) {if(n == 1)return true;        if( A[0] == 0 && n > 1)return false;int max = A[0];int i = 1;for(i = 1; i < n; i++){int temp = A[i] + i;max = (max > temp ? max : temp);if(max <= i && i != n-1)//如果当前节点不是最后一个节点且最大步长到不了下一个节点则返回falsereturn false;}return true;    }};


0 0