动态规划
int mincostTickets(vector<int>& days, vector<int>& costs) {
int dp[368];
memset(dp,0x3f,sizeof(dp));
dp[0] = 0;
int days_idx = 0;
for(int i = 1;i <= days.back();i++)
{
if(i != days[days_idx])
{
dp[i] = dp[i-1];
continue;
}
dp[i] = min(min(dp[max(0,i-1)]+costs[0],dp[max(0,i-7)]+costs[1]),dp[max(0,i-30)]+costs[2]);
days_idx++;
}
return dp[days.back()];
}
dfs
vector<int> day,cost;
int dp[366],vis[366];
int mincostTickets(vector<int>& days, vector<int>& costs){
day = days,cost = costs;
for(int d:days)
vis[d] = 1;
return dfs(1);
}
int dfs(int cur) {
while(cur <= day.back() && vis[cur] == 0)
cur++;
if(cur > day.back())
return 0;
if(dp[cur] != 0)
return dp[cur];
int cost1 = cost[0] + dfs(cur+1);
int cost2 = cost[1] + dfs(cur+7);
int cost3 = cost[2] + dfs(cur+30);
dp[cur] = min(cost1, min(cost2, cost3));
return dp[cur];
}