LeetCode: Jump Game Total 解題報告

來源:互聯網
上載者:User

標籤:style   blog   http   io   os   ar   使用   java   for   

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.

Solutions:

1. DP1
每到一個點 i,我們掃描之前所有的點,如果之前某點j本身可達,並且與current 點可達,表示點i是可達的。

傳回值:DP數組的最後一個值。

View Code

 

2. DP2
最佳化的點1:既然某點可達,肯定前面的點全部是可達的。這個比較好理解。因為你到達i點肯定要經過前面的一個點,這個依次推知可知前面所有的點可達。

所以我們不需要數組來記錄結果,只要預設i點前全部可達就行了。

最佳化點2:如果某點不可達了,直接返回false。不需要再往後計算。

傳回值:如果全部掃完仍沒有返回false,返回true。

 

View Code

 

3. 遞迴
思想是,從前至尾掃描,至第一個距離與本點可達的點j,計算j點是否可達。使用遞迴計算j

點的可達性。

其實這裡還是用到了貪心的思維。在考慮本點是否可達的時候,我們是考慮與本點最遠的一個點是否可達。實際上這也make sense。

假設j點可以到達i點,那麼後面的點可以不管。

(1)因為如果j點不可達,那麼j+1也不可達。如果i不可達,後面的點也可不算。

(2)如果j點可達,並且j點可到達i,那麼也沒有必要再往後計算了。因為結論已經出來了。

  (3) 如果j點可達,但j不可達i,那麼就繼續計算。

 

View Code

 

4. GitHub代碼

CanJump.java

 

References:

感謝http://blog.csdn.net/fightforyourdream/article/details/14219049給予的靈感。

 

LeetCode: Jump Game Total 解題報告

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.