LeetCode 题解工作台
选择矩阵中单元格的最大得分
给你一个由正整数构成的二维矩阵 grid 。 你需要从矩阵中选择 一个或多个 单元格,选中的单元格应满足以下条件: 所选单元格中的任意两个单元格都不会处于矩阵的 同一行 。 所选单元格的值 互不相同 。 你的得分为所选单元格值的 总和 。 返回你能获得的 最大 得分。 示例 1: 输入: grid …
5
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示在 的数中进行选择,且选择的数对应的行的状态为 时的最大得分。初始时 $f[i][j] = 0$,答案为 $f[\textit{mx}][2^m - 1]$。其中 表示矩阵中的最大值,而 表示矩阵的行数。 我们首先对矩阵进行预处理,使用一个哈希表 记录每个数对应的行的集合。然后我们可以使用状态压缩动态规划的方法求解答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个由正整数构成的二维矩阵 grid。
你需要从矩阵中选择 一个或多个 单元格,选中的单元格应满足以下条件:
- 所选单元格中的任意两个单元格都不会处于矩阵的 同一行。
- 所选单元格的值 互不相同。
你的得分为所选单元格值的总和。
返回你能获得的 最大 得分。
示例 1:
输入: grid = [[1,2,3],[4,3,2],[1,1,1]]
输出: 8
解释:

选择上图中用彩色标记的单元格,对应的值分别为 1、3 和 4 。
示例 2:
输入: grid = [[8,7,6],[8,3,2]]
输出: 15
解释:

选择上图中用彩色标记的单元格,对应的值分别为 7 和 8 。
提示:
1 <= grid.length, grid[i].length <= 101 <= grid[i][j] <= 100
解题思路
方法一:状态压缩动态规划
我们定义 表示在 的数中进行选择,且选择的数对应的行的状态为 时的最大得分。初始时 ,答案为 。其中 表示矩阵中的最大值,而 表示矩阵的行数。
我们首先对矩阵进行预处理,使用一个哈希表 记录每个数对应的行的集合。然后我们可以使用状态压缩动态规划的方法求解答案。
对于状态 ,我们可以不选择 这个数,此时 ;也可以选择 这个数,此时我们需要枚举 对应的行的集合 中的每一个行 ,如果 的第 位为 ,则说明我们可以选择 这个数,此时 。
最后我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为矩阵的行数,而 为矩阵中的最大值。
class Solution:
def maxScore(self, grid: List[List[int]]) -> int:
g = defaultdict(set)
mx = 0
for i, row in enumerate(grid):
for x in row:
g[x].add(i)
mx = max(mx, x)
m = len(grid)
f = [[0] * (1 << m) for _ in range(mx + 1)]
for i in range(1, mx + 1):
for j in range(1 << m):
f[i][j] = f[i - 1][j]
for k in g[i]:
if j >> k & 1:
f[i][j] = max(f[i][j], f[i - 1][j ^ 1 << k] + i)
return f[-1][-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on the number of rows, columns, and possible state masks. Worst-case complexity is exponential in row size due to bitmask combinations, but pruning high-value paths reduces practical runtime. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate to sort cells by value and track positions correctly.
- question_mark
Watch if the candidate efficiently uses bitmask dynamic programming to represent row states.
- question_mark
Check if invalid transitions between rows are handled and dominated states are pruned.
常见陷阱
外企场景- error
Failing to correctly map sorted cells back to original grid positions.
- error
Not pruning dominated states, causing unnecessary exponential computation.
- error
Overlooking transitions that violate row or column selection rules, leading to incorrect totals.
进阶变体
外企场景- arrow_right_alt
Maximize score with restrictions on adjacent cell selection.
- arrow_right_alt
Extend to 3D matrices with similar state transition logic.
- arrow_right_alt
Compute maximum score while minimizing the number of selected cells.