【LeetCode】 45. Jump Game II

本文介绍了一种解决Jump Game II问题的算法,通过动态规划(自底向上)找到从数组起始位置到达末尾所需的最小跳跃次数。示例中,输入为[2,3,1,1,4],输出为2,解释了如何从索引0跳到索引1再跳到末尾。代码实现使用C++,并提供了完整的函数和主程序流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

45. Jump Game II

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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

Note:

You can assume that you can always reach the last index.

思路:

DP(自底向上),数组dp[]表示能够到达该位置最小的steps,有一点类似最短上升子序列。

#include<iostream>
#include<vector>
using namespace std;
int minJump(vector<int>& nums)
{
	int* dp = new int[(nums.size())];
	for(int i=1;i<(nums.size());i++) dp[i]=INT_MAX;
	dp[0]=0;
	for(int i=0;i<(nums.size());i++){
		for(int j=i+1;j<=i+nums[i]&&j<(nums.size());j++){
			if(dp[i]+1<dp[j]) dp[j]=dp[i]+1;
		}
	} 
	int ans = dp[(nums.size()-1)];
	delete[] dp;
	return ans;
 } 
 int main(void)
 {
 	vector<int> input;
 	int size;
 	while(cin>>size){
 		int num;
 		for(int i=0;i<size;i++){
 			cin>>num;
 			input.push_back(num);
		 }
		 cout<<minJump(input)<<endl;
	 }
	 return 0;
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值