leetcode:103 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.
思路:動態規劃求解,我們維護兩個變數,一個區域性最優,一個全域性最優。一個表示到目前為止我們能達到的最遠距離,即local = A[i]+i, 另外一個是當前一步出發能跳到的最遠距離,global = max(global, local). 確定了遞推關係,遞推終止條件,達到陣列末尾,如果global > n-1, 說明我們可以用抵達陣列的末尾(global表示最大距離,我們可以選擇剛好的步伐達到末尾)。
複雜度:遍歷一次,O(N),空間O(1) --------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------ 作者:Cindy_niu 來源:CSDN 原文:https://blog.csdn.net/cinderella_niu/article/details/42804385 -------------------------------------------------------------------------------------------------------------------------------------------------------------
class Solution { public: bool canJump(int A[], int n) { if(n == 0) return false; / /空陣列 返回 false int reach = 0; //全域性最遠距離 for(int i = 0; i < n && i <= reach; i++) { reach = max(A[i]+i, reach); } if(reach >= n-1) return true; else return false; } };