思路:若是當前 天數我不想旅遊,那麼花的錢和前一天同樣多。
若是我想旅遊了,那麼我當前的這個票是從哪一天買的呢?
有三種狀況:一天前,七天前,30天前。假設是x天前買的,那麼當前最低票價就是,x天前買票前的花費,假設買的這個票的花費。選擇最低的那個算法
dp[x] = dp[x-1] # 不想旅遊 dp[x] = min(dp[day-1]+costs[0],dp[day-7]+costs[1],dp[day-30]+costs[2])
代碼以下:spa
class Solution(object): def mincostTickets(self, days, costs): last_day,days = days[-1],set(days) dp = [0 for _ in range(366)]+[0]*30 # 第i天所須要的最小費用 for day in range(1,366): dp[day] = dp[day-1] if day not in days else min(dp[day-1]+costs[0],dp[day-7]+costs[1],dp[day-30]+costs[2]) return dp[last_day]
備註:我是算法菜鳥,動態規劃我也是不咋會,寫的確定是很差的,還望海涵!code