jump game II
来源:互联网 发布:python的卷积运算 编辑:程序博客网 时间:2024/05/01 03:18
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.)
超时代码为:
int jump(int A[], int n) {
if(A==NULL || n<2){
return 0;
}
if(n == 2 || A[0] >= n-1)
{
return 1;
}
int* minStepList=new int[n];;
for(int i=0; i<n; ++i)
{
minStepList[i]=0xffff;
}
minStepList[n-1]=0;
minStepList[n-2]=1;
int stepTmp=0;
for(int j=n-3; j>=0; --j)
{
for(int i=A[j]; i>0; --i)
{
if(A[j] >= n-1-j)
{
minStepList[j]=1;
break;
}
if(i+j < n)
{
stepTmp=1+minStepList[i+j];
if(stepTmp < minStepList[j])
{
minStepList[j]=stepTmp;
}
}
else
{
break;
}
}
}
return minStepList[0];
}
后参考别人代码,思路为用一个数组保存第1个结点到第i个结点的最小跳数,该数组为一个递增数组。代码为:
class Solution {
public:
int* dp;
int jump(int A[], int n) {
if(n==0)
{
return INT_MAX;
}
dp = new int[n];
dp[0] = 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(j+A[j]>=i)
{
int tmp = dp[j]+1;
if(tmp < dp[i])
{
dp[i] = tmp//遇到的第一个j结点能够一步跳到i结点的则为最短的
break;
}
}
}
}
return dp[n-1];
}
};
- Jump Game &Jump Game II
- Jump Game/Jump Game II
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- Jump Game II
- Jump Game II
- Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- Jump Game II
- Jump Game II
- Jump Game II
- Jump Game II
- 关于eclipse里配置tomcat以及在tomcat里载入工程的说明
- BF 算法
- ListView滑动删除 ,仿腾讯QQ
- 沟通的五个“魔法”技巧
- Deep learning:十一(PCA和whitening在二维数据中的练习)
- jump game II
- 一个汇集开源硬件的论坛
- 将博客搬至CSDN
- 【shell】构造并遍历二位数组的一种用法
- 怎样提高网站关键词排名
- Android 省市县 三级联动(android-wheel的使用)
- SDN新型网络带来的思考
- 三姑父的房价看过对方离开广东高考大纲
- scala编程系列(5)-scala集set和映射map