[leetcode]Jump Game
生活随笔
收集整理的這篇文章主要介紹了
[leetcode]Jump Game
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
問題敘述性說明:
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.
基本思路:
從每一個可達(dá)的節(jié)點產(chǎn)生新的可達(dá)節(jié)點。
依次類推。但用一個變量head記錄當(dāng)前可達(dá)最遠(yuǎn)的位置。對于i+A[i] < head 能夠剪枝。
請見代碼。
代碼:
bool canJump(int A[], int n) { //C++vector<int> record(n,0);record[0] = 1;if(n == 1)return true;int head = 0;for(int i =0; i < n; i++){if(record[i] == 1 && i+A[i] > head){for(int j = head-i+1; j <= A[i]; j++){if(i+j == n-1)return true;record[i+j] = 1;}head = i+A[i];}}return false;}版權(quán)聲明:本文博客原創(chuàng)文章,博客,未經(jīng)同意,不得轉(zhuǎn)載。
總結(jié)
以上是生活随笔為你收集整理的[leetcode]Jump Game的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MyBatis知多少(10)应用程序数据
- 下一篇: linux awk命令详解,使用syst