Jump Game

来源:互联网 发布:数据库怎么设计 编辑:程序博客网 时间:2024/04/29 03:27

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)设置一个jumpPos 表示从当前这个位置可以调到最后

(2)如果jumpPos为0,那就返回true。否则返回false。


#include <iostream>using namespace std;bool canJump(int A[], int n) {int jumpPos = n - 1;for(int i=n-2;i>=0;i--){if(A[i] >= (jumpPos-i) )jumpPos = i;}if(jumpPos == 0)return true;elsereturn false;}int main(void){int A[] = {2,0,0};int n = sizeof(A)/sizeof(int);cout << canJump(A,n) << endl;system("pause");return 0;}


0 0