larscheng / algo

0 stars 0 forks source link

【Check 78】2024-05-20 - 45. 跳跃游戏 II #184

Open larscheng opened 6 months ago

larscheng commented 6 months ago

45. 跳跃游戏 II

larscheng commented 6 months ago

思路

贪心算法1:逆向搜索,复杂度O(n*n)

贪心算法,正向搜索,复杂度O(n)

class Solution { public int jump(int[] nums) { int lastIndex = nums.length-1; int steps=0; //从最后1个位置开始,找跳跃次数最少的上一个起跳点 while (lastIndex!=0){ //从左向右找,首个符合条件的即为跳跃次数最少的那个 for (int i = 0; i < lastIndex; i++) { if (nums[i] + i >= lastIndex) { lastIndex = i; steps++; break; } } } return steps; } }

```java
    public int jump(int[] nums) {
        int end=0;
        int maxIndex = 0;
        int steps = 0;
        for (int i = 0; i < nums.length-1; i++) {
            maxIndex = Math.max(maxIndex,nums[i]+i);
            if (i == end) {
                end = maxIndex;
                steps++;
            }
        }
        return steps;
    }
larscheng commented 6 months ago

思路

反向动态规划 dp[i] 表示 到达nums[i]的最小跳跃次数 i-1可以跳到i时,次数为dp[i-1]+1 i-2可以跳到i时,次数为dp[i-2]+1 ... 0可以跳到i时,次数为dp[0]+1 dp[i] = min(dp[i-1]+1,dp[i-2]+1,...dp[0]+1)

类似贪心算法,反向搜索,复杂度O(n*n)

代码

        public int jump(int[] nums) {
            int[] dp = new int[nums.length];
            dp[0] = 0;
            for (int i = 1; i < nums.length; i++) {
                dp[i] = Integer.MAX_VALUE;
                for (int j = i - 1; j >= 0; j--) {
                    if (nums[j] + j >= i) {
                        dp[i] = Math.min(dp[i], dp[j] + 1);
                    }
                }
            }
            return dp[nums.length-1];
        }
    }