【发布时间】:2021-10-05 00:49:32
【问题描述】:
我正在尝试解决this problem,我可以使用回溯来解决它。但是,鉴于存在多个变量(天数数组的索引不断变化,并且每天我们尝试不同的成本),我无法想出正确的方法来记忆它,因此需要一些帮助。这是我的代码,它似乎工作正常,但它显然正在重复计算
private int[] durations = {1, 7, 30};
public int mincostTickets(int[] days, int[] costs) {
if (days.length == 0) return 0;
return backtrack(days, costs, 0, 0, 0);
}
private int backtrack(int[] days, int[] costs, int index, int costSoFar, int window) {
if (index >= days.length ) {
return costSoFar;
}
int cost = Integer.MAX_VALUE;
for (int j = 0; j < costs.length; j++) {
int currCost = 0;
if (days[index] >= window ) {
currCost = backtrack(days, costs, index + 1, costSoFar + costs[j], days[index] + durations[j]);
} else {
currCost = backtrack(days, costs, index + 1, costSoFar, window);
}
cost = Math.min(cost, currCost);
}
return cost;
}
另外,如果你能帮助我理解这里的时间复杂度,那就太好了!
【问题讨论】:
标签: java algorithm memoization