656 Coin Path
656. Coin Path
1. Question
Given an arrayA
(index starts at1
) consisting of N integers: A1, A2, ..., AN and an integerB
. The integerB
denotes that from any place (suppose the index isi
) in the arrayA
, you can jump to any one of the place in the arrayA
indexedi+1
,i+2
, …,i+B
if this place can be jumped to. Also, if you step on the indexi
, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexedi
in the array.
Now, you start from the place indexed1
in the arrayA
, and your aim is to reach the place indexedN
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 indexedN
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:
Example 2:
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 such
i
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].
2. Implementation
(1) DP
思路: 从后往前扫一遍数组,用两个数组dp和preIndex分别记录以下信息,dp[i]表示从开头到位置i的min cost, preIndex记录在min cost path中位置i前的一个位置
3. Time & Space Complexity
时间复杂度O(n^2), 空间复杂度O(n)
Last updated