Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1i+2, …, i+B if this place can be jumped to. Also, if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexed i in the array.

Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed Nusing the minimum coins. You need to return the path of indexes (starting from 1 to N) in the array you should take to get to the place indexed N using minimum coins.

If there are multiple paths with the same cost, return the lexicographically smallest such path.

If it's not possible to reach the place indexed N then you need to return an empty array.

Example 1:

Input: [1,2,4,-1,2], 2
Output: [1,3,5]

Example 2:

Input: [1,2,4,-1,2], 1
Output: []

Note:

  1. Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if at the first iwhere Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.
  2. A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100].
  3. Length of A is in the range of [1, 1000].
  4. B is in the range of [1, 100].

参考了lee215的解答:

设dp数组中dp[i]为到第i个位置最小花费,那么dp数组就可以求出来。递推公式为

for i in 1 : len:

dp[i] = min(dp[j] + A[i-1])  for j in range(max(0,j-B),j)

大意就是从当前位置往回找B个位置,并把之前的花费和当前的A相加,求最小值。

而又要返回字典序的最小index。在python中可以用min求数组的最小,就是字典序。

Runtime: 236ms, beats 24.14% 时间复杂度(N*B*N),最后一个N是因为比较数组的时候,数组长度是N,空间复杂度(N*N)

class Solution:
def cheapestJump(self, A, B):
"""
:type A: List[int]
:type B: int
:rtype: List[int]
"""
if not A or A[0] == -1: return 0
dp = [[float('inf')] for _ in A]
dp[0] = [A[0], 1]
for j in range(1, len(A)):
if A[j] == -1: continue
dp[j] = min([dp[i][0] + A[j]] + dp[i][1:] + [j+1] for i in range(max(0,j-B),j))
return dp[-1][1:] if dp[-1][0] != float('inf') else []

看来还能再优化,

这是另一种解法,利用堆的性质,同样把花费和路径都放进堆中,每次取最小的一个花费,加上当前的花费再推进堆中。时间复杂度(N*log(B)*N),优化了选取的步骤,但堆中元素每一次比较花费的时间还是O(N)的。

Runtime:68ms beats: 100%

def cheapestJump(self, A, B):

        N = len(A)
A = ['dummy'] + A
if A[N] == -1: return []
heap = [(A[N], [N])]
new_path = [N]
for i in range(N-1, 0, -1): # From N-1 sweeping to 1
if A[i] == -1: continue while heap:
cost, path = heapq.heappop(heap)
if path[0] <= i + B: break #当前的index加上B后应该大于之前保存的路径的第一个,这样才能连的上。
else: # exhausted heap without finding the previous path
return [] new_cost = cost + A[i]
new_path = [i] + path heapq.heappush(heap, (new_cost, new_path))
heapq.heappush(heap, (cost, path))
return new_path

这题如果用C++,JAVA来做,没有python的min能比较数组或者tuple的性质就麻烦一点。

LC 656. Coin Path 【lock, Hard】的更多相关文章

  1. LC 660. Remove 9 【lock, hard】

    Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... So now, you will have ...

  2. LC 163. Missing Ranges 【lock, hard】

    Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, up ...

  3. LC 871. Minimum Number of Refueling Stops 【lock, hard】

    A car travels from a starting position to a destination which is target miles east of the starting p ...

  4. LC 425. Word Squares 【lock,hard】

    Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...

  5. LC 499. The Maze III 【lock,hard】

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  6. LC 759. Employee Free Time 【lock, hard】

    We are given a list schedule of employees, which represents the working time for each employee. Each ...

  7. LC 245. Shortest Word Distance III 【lock, medium】

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  8. LC 244. Shortest Word Distance II 【lock, Medium】

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  9. LC 302. Smallest Rectangle Enclosing Black Pixels【lock, hard】

    An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black ...

随机推荐

  1. mysql提示错误[Error Code] 1290 - The MySQL server is running with the --secure-file-priv option解决办法

    1.进入mysql查看secure_file_prive的值 $mysql -u root -p mysql>SHOW VARIABLES LIKE "secure_file_priv ...

  2. demjson

    demjson.decode() 可以扩展json的类型

  3. openssh的服务端配置文件

    一.因为部分配置长时间不使用就忘了,为了方便查阅,我在这里检点写一些比较有用的ssh配置选项. PortListenAddress ip       #监听自己的哪个端口,默认是都监听的,如果指定了I ...

  4. Mybatis问题-Type interface com.zzu.ssm.dao.UserMapper is not known to the MapperRegistry

    1. mapper.xml中namespace名称是否与dao接口包名一致 2. 在mybatis配置文件中注册mapper

  5. 1 request模块

    官方文档真是好用的一匹 官方文档:https://2.python-requests.org//zh_CN/latest/index.html 参考blog:https://www.cnblogs.c ...

  6. vue2.0 + element-ui2实现分页

    当我们向服务端请求大量数据的时候,并要在页面展示出来,怎么办?这个时候一定会用到分页. 本次所使用的是vue2.0+element-ui2.12实现一个分页功能,element-ui这个组件特别丰富, ...

  7. [人物存档]【AI少女】【捏脸数据】1223今日份的推荐

    点击下载(城通网盘):AISChaF_20191112214754919.png 点击下载(城通网盘):AISChaF_20191111205924765.png

  8. CSS3 box-sizing:content-box | border-box

    box-sizing:content-box | border-box 默认值:content-box 适用于:所有接受width和height的元素 继承性:无 content-box: paddi ...

  9. MessagePack Java 0.6.X 不使用注解(annotations)来序列化

    如果你不能添加 @Message 到你的定义对象中但是你还是希望进行序列化.你可以使用 register 方法来在类中启用序列化对象. 如下的代码所示: MessagePack msgpack = n ...

  10. 51 Nod 1163 最高的奖励

    1163 最高的奖励  基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题  收藏  关注 有N个任务,每个任务有一个最晚结束时间以及一个对应的奖励.在结束时间之前完成 ...