Jump Game II
来源:互联网 发布:百度源码 编辑:程序博客网 时间:2024/06/16 00:22
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
python
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方法,java可以正常通过,但是python超时
java
public class Solution { /* * @param A: A list of integers * @return: An integer */ public int jump(int[] A) { // write your code here if (A == null || A.length == 0) { return -1; } // state int[] f = new int[A.length]; // initialize f[0] = 0; for (int i = 1; i < A.length; i++) { f[i] = Integer.MAX_VALUE; } // function for (int i = 1; i < A.length; i++) { for (int j = 0; j < i; j++) { if (f[j] != Integer.MAX_VALUE && A[j] + j >= i) { f[i] = Math.min(f[j] + 1, f[i]); } } } // answer return f[A.length - 1]; }}
python
class Solution: """ @param: A: A list of integers @return: An integer """ def jump(self, A): # write your code here if A is None or len(A) == 0: return -1 # state and initialize f = [float('inf')] * len(A) f[0] = 0 # function for i in range(1, len(A)): for j in range(i): if f[j] != float('inf') and A[j] + j >= i: f[i] = min(f[j] + 1, f[i]) return f[-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
- rosmsg show Num时could not find msg Num
- OpenStack-M版(Mitaka)搭建基于(Centos7.2)+++六、Openstack网络服务(neutron)上
- 斐波那契数列-C语言实现
- Qt--工程配置
- 对Opengl中的帧缓冲的一些理解(延迟渲染,后处理等)
- Jump Game II
- kinect1v使用步骤
- VT VMCS结构信息
- Volatile原理
- 需要产生随机数
- Window.location.href以post方式传递参数的方法
- Android仿iphone时间轴相册
- 钛极OS(TiJOS)物联网操作系统之小试牛刀(1)——灯、按键
- flume学习(三):flume将log4j日志数据写入到hdfs