题目
示例
思路
- 从前往后进行动态规划
dp[i]表示从days[i]开始到days[days.length-1]的最小花费
dp[i] = min(dp[i+1]+cost[0],dp[i+7]+cost[1],dp[i+30]+cost[2]);
- 限制条件
如果days[j] < days[i]+durations[k],j++,一直遍历到这次花费不能旅行的那一天,因为durations[k]是单调递增的,所以j一直增下去就可以了,不需要从i开始。
j < days.length && days[j] < days[i]+durations[k];
- 有一些状态可以复用
初始化时:
Integer[] totalCost = new Integer[days.length];
此时totalCost[i] = null,所以当totalCost[i] != null时,说明该状态已经计算过,可以直接使用,不然会超时。
具体代码
class Solution {
int[] days, costs;
Integer[] totalCost;
int[] durations = new int[]{1, 7, 30};
public int mincostTickets(int[] days, int[] costs) {
this.days = days;
this.costs = costs;
totalCost = new Integer[days.length];
return dp(0);
}
public int dp(int i){
if(i >= days.length){
return 0;
}
if(totalCost[i] != null){
return totalCost[i];
}
int j = i;
totalCost[i] = Integer.MAX_VALUE;
for(int k = 0;k < 3;k++){
while(j < days.length && days[j] < days[i]+durations[k]){
j++;
}
totalCost[i] = Math.min(totalCost[i],dp(j)+costs[k]);
}
return totalCost[i];
}
}
参考资料
https://leetcode-cn.com/problems/minimum-cost-for-tickets/solution/zui-di-piao-jie-by-leetcode-solution/