leetcode55. 跳跃游戏(java & python3)

看视频学习两种方法 呜呜呜

java:

动态规划

class Solution {
    public boolean canJump(int[] nums) {

        boolean[] dp = new boolean[nums.length];
        dp[0] = true;

        for(int i = 1; i < nums.length; i++){
            for(int j = 0; j < i; j++){
                if(dp[j] & nums[j] + j >= i){
                    dp[i] = true;
                    break;
                }
            }
        } 
        return dp[nums.length - 1];
    }
}

贪心:

class Solution {
    public boolean canJump(int[] nums) {
        if(nums.length ==1){
            return true;
        }
        int cover = nums[0];
        for(int i = 0; i <= cover; i++){
            cover = Math.max(cover, nums[i] + i);
            if(cover >= nums.length - 1){
                return true;
            }
        }
        return false;
    }
}

python3:

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n, cover = len(nums), 0
        for i in range(n):
            if i <= cover:
                cover = max(cover, nums[i] + i)
                if cover >= n - 1:
                    return True
        return False

你可能感兴趣的:(学习做题leetcode,java,leetcode,python,贪心,动态规划)