补一下3
先将出现过的数字大到小排(去除重复)
以这个sorted_values为基础,从大的开始选,这样就可以很轻松地排除重复问题
(这边没想到好亏)
然后就根据选的value,来看哪些row有出现这个value,就遍历这些row (取or不取)
下一层就传第二大的value继续做一样的事情,就一般的dfs
要记下跑过哪些row,那些row就不跑了
以row为节点的traversal,就顶多2^10组,比直接brute force好很多
等等再来看4,比赛的时候连4的题目都没看==
def maxScore(self, grid: List[List[int]]) -> int:
m,n = len(grid), len(grid[0])
mp = defaultdict(set)
value_set = set()
for row_idx, r in enumerate(grid):
for n in r:
value_set.add(n)
mp[n].add(row_idx)
value_sorted = sorted(list(value_set))[::-1]
ans = 0
def dfs(cur_idx, cur_sum, select_rows):
nonlocal ans
if len(select_rows) == m or cur_idx>=len(value_sorted):
ans = max(ans, cur_sum)
return
if_searched = False
# print(cur_idx, len(select_rows), select_rows)
for r_idx in mp[value_sorted[cur_idx]]:
if r_idx not in select_rows:
select_rows.add(r_idx)
dfs(cur_idx+1, cur_sum+value_sorted[cur_idx], select_rows)
select_rows.remove(r_idx)
if_searched = True
if if_searched == False:
dfs(cur_idx+1, cur_sum, select_rows)
dfs(0,0,set())
return ans