LC 3276. 选择矩阵中单元格的最大得分
https://leetcode.cn/problems/select-cells-in-grid-with-maximum-score/description/
这题一个关键是怎么进行探索,为了保证不重复的话,我们可以按照每个单元格值从小到大进行搜索,这样的话就会比较简单。
class Solution: def maxScore(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) import functools @functools.cache def dfs(st, M): if st == (1 << n) - 1: return 0 ans = 0 for i in range(n): if st & (1 << i) == 0: for j in range(m): if grid[i][j] > M: r = dfs(st | (1 << i), grid[i][j]) ans = max(r + grid[i][j], ans) return ans ans = dfs(0, 0) return ans