Leetcode Jump Game II

题意:给出从当前节点能跳的最大步数,求最少要跳多少步能到达终点。
思路:枚举跳的步数,用BFS实现。
class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size() < 2) return 0;
        
        int step = 0, maxJump = 0, next = 0;
        while(maxJump < nums.size()) {
            step ++;
            int nextMaxJump = 0;
            for(int i = next; i <= maxJump; ++ i, next ++) {
                nextMaxJump = max(nextMaxJump, i + nums[i]);
                if(nextMaxJump >= nums.size() - 1) return step; 
            }
            // next = maxJump;
            maxJump = nextMaxJump;
        }
        
        return step;
    }
};

猜你喜欢

转载自blog.csdn.net/markpen/article/details/68955565