12.1—贪心法—Jump Game

来源:互联网 发布:社交网络剧情 编辑:程序博客网 时间:2024/05/19 19:58
描述
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.

#include<iostream>using namespace std;bool JumpGame(int a[], int n){if (a == NULL || n <= 0)return false;int reachindex = a[0];if (reachindex >= n - 1)return true;for (int i = 0; i < n-1; i++){if (a[i] == 0 && reachindex == i)return false;if (a[i] + i > reachindex)reachindex = a[i] + i;if (reachindex >= n - 1)return true;}}int main(){const int n = 5;int a[n] = { 3,2,1,0,4};bool flag = JumpGame(a, n);if (flag)cout << "you are able reach int last index!" << endl;elsecout << "No!" << endl;}

原创粉丝点击