码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Jump Game II(跳跃游戏2)

时间:2015-12-01 21:04:53      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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

如题,求到达末位最少的跳的次数。

 1 class Solution {
 2 private:
 3     int dp[100000];
 4 public:
 5     int jump(vector<int>& nums) {
 6         int maxPos = 0;
 7         dp[0] = 0;
 8         int pos = 0;
 9         int sz = nums.size();
10         for(int i = 0; i <= maxPos; ++i){
11             pos = i + nums[i];
12             if(pos >= sz)
13                 pos = sz - 1;
14             if(pos > maxPos){
15                 for(int j = maxPos + 1; j <= pos; ++j)
16                     dp[j] = dp[i] + 1;
17                 maxPos = pos;
18             }
19             
20             if(maxPos == sz - 1)
21                 return dp[sz - 1];
22         }
23 
24     }
25 };

 

LeetCode OJ:Jump Game II(跳跃游戏2)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/5002547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!