Jump Game II
来源:互联网 发布:json rpc restful 编辑:程序博客网 时间:2024/06/05 09:23
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.)
代码一:dfs,即迭代,小数据可以,大数据会因为迭代太深而超时。
public static void dfs(int[] A, List<Integer> step, int jump, int start, int end){if(start == end){step.add(jump);return;}else if(start > end)return;else{if(start < end){for(int i = 1; i <= A[start]; i++)dfs(A, step, jump + 1, start + i, end);}}}public static int jump(int[] A) { List<Integer> result = new ArrayList<Integer>(); dfs(A, result, 0, 0, A.length - 1); int min = result.get(0); for(int i = 1; i < result.size(); i++) if(min > result.get(i)) min = result.get(i); return min; }个人理解:涉及到层次即回溯的,可以考虑到dfs,算法不好,努力学习中。
代码二:动态规划。dp[i]代表跳到下标i的位置最少的步数。
dp[0] = 0;
dp[i]: 从位置0~ j~ i - 1中,若d[j] + j >= i, d[i] = d[j] + 1;
public static int jump2(int[] A) {int length = A.length;if(A.length <= 1)return 0;int[] dp = new int[length];dp[0] = 0;for(int i = 1; i < length; i++){for(int j = 0; j < i; j++){if(j + A[j] >= i){dp[i] = dp[j] + 1;break;}}}return dp[length - 1];}
0 0
- 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
- Sql Server 锁机制
- 游戏开发过程详细介绍
- 数据挖掘在金融行业十大应用
- KVC方法快速为数据对象赋值
- Handling Non-Blocking I/O Errors in OpenSSL
- Jump Game II
- 消息队列软件产品大比拼
- css float
- 面向对象、匿名对象、成员、封装、主函数、成员变量、局部变量、构造函数、this、静态、主函数
- php函数call_user_func和call_user_func_array详解
- 数据挖掘入门——分词
- java常用流处理工具StreamTool 常见的InputStream流转字符串, 转字节数组等等
- 从UITableView删除一行与Model-View-Controls模型
- 字符串,字典,数组写入本地文件和从本地文件读取