LC 656. Coin Path 【lock, Hard】
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+1
, i+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 N
using 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:
- Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if at the first
i
where Pai and Pbi differ, Pai < Pbi; when no suchi
exists, thenn
<m
. - A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100].
- Length of A is in the range of [1, 1000].
- 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】的更多相关文章
- 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 ...
- LC 163. Missing Ranges 【lock, hard】
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, up ...
- 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 ...
- LC 425. Word Squares 【lock,hard】
Given a set of words (without duplicates), find all word squares you can build from them. A sequence ...
- 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 ...
- LC 759. Employee Free Time 【lock, hard】
We are given a list schedule of employees, which represents the working time for each employee. Each ...
- 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 ...
- 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 ...
- 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 ...
随机推荐
- 经典i++和++i问题(附带运算符优先级问题)
转自 https://blog.csdn.net/mustard1020/article/details/79617865 1.i++和++i的区别 (1)i++简单来说就是先用i的值来参加表 ...
- php将数组中某个元素置顶设为第一个元素
一个数组$a0有N个元素,要将其中第3个元素,排在数组的首位. 第一种做法是: 取出第3个元素,赋值给变量$a unset 第3个元素 array_unshift 将$a添加到数组头部. 如果是数字下 ...
- 转 shell中的多进程【并发】
原文地址https://bbs.51cto.com/thread-1104907-1-1.html 根据我个人的理解, 所谓的多进程 只不过是将多个任务放到后台执行而已,很多人都用到过,所以现在讲的主 ...
- 将本地代码使用Git上传更新至Github
注册.配置git 1. 首先注册git image 2.然后下载.配置git 百度“git下载”,然后默认安装,注意的是最后要添加环境变量,最后安装结果如下: image 配置如下: 1.设置本地的s ...
- c# 获取api 数据
private string GetDataFromServerApi(string url, string body) { string str = ""; try { Http ...
- linux内核 内存管理
以下内容汇总自网络. 在早期的计算机中,程序是直接运行在物理内存上的.换句话说,就是程序在运行的过程中访问的都是物理地址. 如果这个系统只运行一个程序,那么只要这个程序所需的内存不要超过该机器的物理内 ...
- 如何判断元素是否在可视区域ViewPort
个性签名: 生如夏花,逝如冬雪:人生如此,何悔何怨. 前言: 经常需要计算元素的大小或者所在页面的位置,offsetWidth,clientWidth,scrollWidth,scrollTop这几个 ...
- PHP swoole TCP服务端和客户端
服务端 <?php $server = ,SWOOLE_PROCESS,SWOOLE_SOCK_TCP); $server->set(array( , )); $server->on ...
- Eclipse 的 CheckStyle 插件
Eclipse 的 CheckStyle 插件 1.简介 Checkstyle 是 SourceForge 下的一个开源项目,提供了一个帮助 JAVA 开发人员遵守某些编码规范的工具.它能进行自动化代 ...
- PC监听鼠标和键盘事件,定时无响应退出
直接上代码: window.onload = function () { initScreenSaver(); } //0912 add function ScreenSaver(settings){ ...