[LeetCode] 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.

 

用貪心策略,剛開始step = A[0],到下一步step--, 並且取step = max(step, A[1]),這樣step一直是保持最大的能移動步數,局部最優也是全局最優。

 1 class Solution {
 2 public:
 3     bool canJump(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (n == 0)
 7             return false;
 8             
 9         int step = A[0];
10         
11         for(int i = 1; i < n; i++)
12             if (step > 0)
13             {
14                 step--;
15                 step = max(step, A[i]);
16             }
17             else
18                 return false;
19                 
20         return true;
21     }
22 };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM