Leetcode Weekly Contest 192
Contents
Did well on the first two problems; spent multiple iterations on the third problem; got stuck for the last one.
3. Design Browser History
This is a problem simulating browse history behavior. I spent too many iterations on debugging the offset computation. To improve, focus on the distinction between length and index.
4. Paint House III
I found out the state definition early enough(about 5 minutes in). However got stuck for a long time on how to handle the house is already patined case. As result I was not able to reduce the problem all the way to base case. Eventually failed to solve this problem in time.
Here is a version after the contest:
# 6/7/2020
class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
# Paint ith house in color j, resulting in k groups.
@functools.lru_cache(None)
def search(i, j, k):
if i < 0 and k <= 1:
return 0
if k > i + 1 or k < 1:
return math.inf
if houses[i] and j != houses[i] - 1: # color starts from 1
return math.inf
prev_cost = math.inf
for c in range(n):
if c == j:
prev_cost = min(prev_cost, search(i - 1, j, k))
else:
prev_cost = min(prev_cost, search(i - 1, c, k - 1))
paint_cost = cost[i][j] * (not houses[i])
return paint_cost + prev_cost
res = min(search(m - 1, c, target) for c in range(n))
return res if res < math.inf else -1
Author Michael
LastMod 2020-06-07