[leetcode] Jump Game II

来源:互联网 发布:淘宝上次认证信息地址 编辑:程序博客网 时间:2024/06/04 21:16

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

DP实现,用dp[i]来表示到达i的最小跳数。由于A[i]表示i能跳的最大步长,dp[n]应该是一个递增数组。所以一旦找到一个点j可以更新dp[i]即break。

int jump(int A[], int n) {        vector<int> dp(n, 0);        for (int i = 1; i < n; ++i)            dp[i] = INT_MAX;        for (int i = 1; i < n; ++i)        {            for (int j = 0; j < i; ++j)            {                if (A[j] + j >= i)                {                    if (dp[j] + 1 < dp[i])                    {                        dp[i] = dp[j] + 1;                        break;                    }                }            }        }        return dp[n - 1];    } 


0 0
原创粉丝点击