leetcode題目講解(Python): 55 跳躍遊戲 (55 Jump Game)

Problem

Jump Game

Solution

Back-forward

  1. 首先把 list 裏最後一項作爲目標。
  2. 由後向前尋找可以到達目標的位置i(滿足 i + nums[i] >= des)。
  3. 如果發現滿足條件的位置 i ,把目標更新爲位置 i,如果 i 爲 0,返回 True,否則然後開始下一個循環。
  4. 如果找不到滿足條件的 i, 返回 False

Explanation in English :

  1. Set des(destination) equals to the last item in the “nums”.
  2. From back to front finding i which can meet the condition: i + nums[i] >= des
  3. If we can find i satisfies the condition, set des = i. If i == 0, then return True, otherwise start the next loop.
  4. If there is no i can meet the condition, return False.
class Solution:
    def canJump(self, nums) -> int:
        if not nums or len(nums) == 1:
            return True

        des = len(nums) - 1

        for I in range(des - 1, -1, -1):
            if I + nums[I] >= des:
                des = i
            if des == 0:
                return True

Greedy

Chinese:
我們也可以通過修改問題45 的代碼通過貪婪算法得到答案。

English:
We can easily change our code in Problem 45 to get the solution.

class Solution:
    def canJump(self, nums) -> int:
        if not nums or len(nums) == 1:
            return False

        des = len(nums) - 1

        I = 0
        max_range = 0
        nxt = 0
        while I < des:
            if I + nums[I] >= des:
                return True
            for r in range(I + 1, I + nums[I] + 1):
                if r + nums[r] > max_range:
                    max_range = r + nums[r]
                    nxt = r
            if I == nxt:
                return False
            else:
                I = nxt

如何刷題 : Leetcode 題目的正確打開方式

我的GitHub : Jedi-XL

其他題目答案:leetcode題目答案講解彙總(Python版 持續更新)

我的博客裏還有其他好東西: 苔原帶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章