LeetCode - jump game II

LeetCode - jump game II

    • LeetCode - jump game II
      • 题目描述
      • 思路阐述
        • DPTLE -time limited exceeded
        • BFS-On
        • 贪心-On
      • 代码实现
        • dp
        • BFS
        • 贪心

1.题目描述

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
题目无法理解的看上一篇博客—–jump game I


2.思路阐述

1. DP:(TLE -time limited exceeded)

  • 设状态为 f[i],表示从第 0 层出发,走到 A[i] 时用的最小步数,则状态转移方程为:
    f(i) = 0, i==0
    f (i) = min {f(j)+i-j} , i>0时 j为可以直接跳到i的位置,即A[j] >= i-j i >j.
    时间复杂度O(n^2)

  • maxPos(i):走i步最远的位置

2. BFS-O(n)

[2 3 1 1 4] 初始,push 2, 第一步 push A[0+1] , A[0+2] ; delete 2
jump++;
第二步, jump++; push 4, 完成。
minJump =2;

可以看成处理最短路径问题。
每两个相隔点都有边长为1的边,同时,A[i]表示从i 到i+1, ….., i+A[i]存在一条边
所以代码相通的,可以多思考一下之间的关系

3. 贪心-O(n)

Let’s say the range of the current jump is [curBegin, curEnd], curFarthest is the farthest point that all points in [curBegin, curEnd] can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps, as the following:


3.代码实现

1. dp

//最丑陋的dp
class Solution {
    public :
    int jump(vector<int> nums) {
        int n = nums.size();
        int*f = new int[n];
        for(int i = 0; i < n; i++) {
            f[i] = 2000;  //初始化f[i]。 
        }
        f[0]= 0;  //f(i)表示 到i的最小步数。

        for(int i = 0; i< n; i++) {
            for(int j = 0; j< i; j++) {
                if(nums[j] >= i-j) {
                    if(f[j]+1 < f[i]) f[i] =f[j]+1;
                }
            } 

        }
        for(int i = 0; i < n; i++) {
            cout<" "; 
        }
        cout << endl;
        return f[n-1]; 
    }
};

2. BFS

int jump(int A[], int n) {
     if(n<2)return 0;
     int level=0,currentMax=0,i=0,nextMax=0;

     while(currentMax-i+1>0){       //nodes count of current level>0
         level++;
         for(;i<=currentMax;i++){   //traverse current level , and update the max reach of next level
            nextMax=max(nextMax,A[i]+i);
            if(nextMax>=n-1)return level;   // if last element is in level+1,  then the min jump=level 
         }
         currentMax=nextMax;
     }
     return 0;
 }

3. 贪心

public int jump(int[] A) {
    int jumps = 0, curEnd = 0, curFarthest = 0;
    for (int i = 0; i < A.length - 1; i++) {
        curFarthest = Math.max(curFarthest, i + A[i]);
        if (i == curEnd) {
            jumps++;
            curEnd = curFarthest;
        }
    }
    return jumps;
}

没事多看代码理解。保证贴的代码对应的算法是对应的,不会说贪心的贴了dp的代码。还是要多看多理解。

你可能感兴趣的:(算法分析与设计)