classBrowserHistory { vector<string> history; int index; int last; public: BrowserHistory(string homepage) { history.resize(5000); index = 0; last = 0; history[0] = move(homepage); } voidvisit(string url){ ++index; history[index] = url; last = index; } string back(int steps){ if (index >= steps) { index = index - steps; } else { index = 0; } return history[index]; } string forward(int steps){ if (index + steps <= last) { index = index + steps; } else { index = last; } return history[index]; } };
/** * Your BrowserHistory object will be instantiated and called as such: * BrowserHistory* obj = new BrowserHistory(homepage); * obj->visit(url); * string param_2 = obj->back(steps); * string param_3 = obj->forward(steps); */
状态转移方程: dp[i][t][lastColor] = min(paint cost [i:j) use color + dp[j][t-1][color]) for j in range(i,m+1) for color in range(1,n+1).
需要注意一些剪枝和paint函数的有效实现,因为此TLE2发。
时间复杂度: O(m * target * n * m * n),
空间复杂度: O(m * target * n).
classSolution: defminCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int: @lru_cache(None) defpaint(i, j, color): if i == j: return0 else: if houses[i] == color: return paint(i+1, j, color) elif houses[i] == 0: return paint(i+1, j, color) + cost[i][color-1] else: returnfloat('inf') @lru_cache(None) defdp(i: int, t: int, lastColor: int) -> int: if t == 1: ans = float('inf') for color inrange(1, n + 1): if color == lastColor: continue pre = paint(i, m, color) ans = min(ans, pre) return ans else: ans = float('inf') seenColors = 0 for j inrange(i + 1, m): if houses[j-1] != 0: if seenColors != 0and seenColors != houses[j-1]: return ans seenColors = houses[j-1] if seenColors == 0: for color inrange(1, n + 1): if color == lastColor: continue pre = paint(i, j, color) if pre < ans: ans = min(ans, pre + dp(j, t-1, color)) else: color = seenColors if color != lastColor: pre = paint(i, j, color) if pre < ans: ans = min(ans, pre + dp(j, t-1, color)) return ans ans = dp(0, target, -1) return ans if ans < float('inf') else -1