题目:
在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。
火车票有三种不同的销售方式:
一张为期一天的通行证售价为 costs[0] 美元;
一张为期七天的通行证售价为 costs[1] 美元;
一张为期三十天的通行证售价为 costs[2] 美元。
通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。
返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。
算法二:
现在,我们令 dp(i) 表示能够完成从第 days[i] 天到最后的旅行计划的最小花费(注意,不再是第 i天到最后的最小花费)。令 j1 是满足 days[j1]>=days[i]+1的最小下标,j7是满足 days[j7]>=days[i]+7+7 的最小下标, j30 是满足 days[j30]>=days[i]+30的最小下标,那么就有:
dp(i)=min(dp(j1)+costs[0],dp(j7)+costs[1],dp(j30)+costs[2])
public class Solution {
方法一:
// int[] costs;
// Integer[] memo;
// Set<Integer> dayset;
//
// public int mincostTickets(int[] days, int[] costs) {
// this.costs = costs;
// memo = new Integer[366];
// dayset = new HashSet();
// for (int d: days) {
// dayset.add(d);
// }
// return dp(1);
// }
//
// public int dp(int i) {
// if (i > 365) {
// return 0;
// }
// if (memo[i] != null) {
// return memo[i];
// }
// if (dayset.contains(i)) {
// memo[i] = Math.min(Math.min(dp(i + 1) + costs[0], dp(i + 7) + costs[1]), dp(i + 30) + costs[2]);
// }
// else {
// memo[i] = dp(i + 1);
// }
// return memo[i];
// }
方法二:
int[] days;
int[] costs;
int[] dayindex = {1, 7, 30};
Integer[] memo;
public int mincostTickets(int[] days, int[] costs) {
this.days = days;
this.costs = costs;
memo = new Integer[days.length];
return dp(0);
}
public int dp(int i) {
if (i >= days.length) return 0;
if (memo[i] != null) return memo[i];
int j = i;
memo[i] = Integer.MAX_VALUE;
for (int k = 0; k < 3; k++) {
while (j < days.length && days[j] < days[i] + dayindex[k]) {
j++;
}
memo[i] = Math.min(memo[i], dp(j) + costs[k]);
}
return memo[i];
}
}