现在的位置: 首页 > 综合 > 正文

Leetcode ump Game II

2019年03月10日 ⁄ 综合 ⁄ 共 779字 ⁄ 字号 评论关闭

题目:

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.)

解题:

基本和ump Game相同,需要中间处理一下,比如数据 3 2 1,后面2 1就没有用,不用遍历这些数据

代码:

class Solution {
public:
    int jump(int A[], int n) {
        bool mark[n];
        memset(mark, 0, sizeof(mark));
        int mx = -1;
        for(int i = 0; i < n; i ++) {
            if(A[i] <= mx) {
                mark[i] = 1;
            }
            mx = max(mx, A[i]);
            mx --;
        }

        int f[n];
        for(int i = 0; i < n; i ++)
            f[i] = INF;
        f[0] = 0;
        for(int i = 0; i < n; i ++) {
            if(mark[i]) continue;
            for(int j = 1; j <= A[i] && i + j < n; j ++) {
                if(mark[i + j] && i + j != n - 1) continue;
                f[i + j] = min(f[i + j], f[i] + 1);
            }
        }
        return f[n - 1];
    }
private:
    static const int INF = 1 << 30;
};

抱歉!评论已关闭.