LeetCode 题解工作台
连通两组点的最小成本
给你两组点,其中第一组中有 size 1 个点,第二组中有 size 2 个点,且 size 1 >= size 2 。 任意两点间的连接成本 cost 由大小为 size 1 x size 2 矩阵给出,其中 cost[i][j] 是第一组中的点 i 和第二组中的点 j 的连接成本。 如果两个组中…
5
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们记第一组的点数为 ,第二组的点数为 。 由于 $1 \leq n \leq m \leq 12$,因此,我们可以用一个整数来表示第二组中点的状态,即二进制表示的一个长度为 的整数,其中第 位为 表示第二组中的第 个点与第一组中的点连通,为 表示不连通。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你两组点,其中第一组中有 size1 个点,第二组中有 size2 个点,且 size1 >= size2 。
任意两点间的连接成本 cost 由大小为 size1 x size2 矩阵给出,其中 cost[i][j] 是第一组中的点 i 和第二组中的点 j 的连接成本。如果两个组中的每个点都与另一组中的一个或多个点连接,则称这两组点是连通的。换言之,第一组中的每个点必须至少与第二组中的一个点连接,且第二组中的每个点必须至少与第一组中的一个点连接。
返回连通两组点所需的最小成本。
示例 1:

输入:cost = [[15, 96], [36, 2]] 输出:17 解释:连通两组点的最佳方法是: 1--A 2--B 总成本为 17 。
示例 2:

输入:cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]] 输出:4 解释:连通两组点的最佳方法是: 1--A 2--B 2--C 3--A 最小成本为 4 。 请注意,虽然有多个点连接到第一组中的点 2 和第二组中的点 A ,但由于题目并不限制连接点的数目,所以只需要关心最低总成本。
示例 3:
输入:cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]] 输出:10
提示:
size1 == cost.lengthsize2 == cost[i].length1 <= size1, size2 <= 12size1 >= size20 <= cost[i][j] <= 100
解题思路
方法一:状态压缩 + 动态规划
我们记第一组的点数为 ,第二组的点数为 。
由于 ,因此,我们可以用一个整数来表示第二组中点的状态,即二进制表示的一个长度为 的整数,其中第 位为 表示第二组中的第 个点与第一组中的点连通,为 表示不连通。
接下来,我们定义 表示第一组中的前 个点已经全部连通,且第二组中的点的状态为 时的最小成本。初始时 ,其余值均为正无穷大。答案即为 。
考虑 ,其中 。我们可以枚举第二组中的每个点 ,如果点 与第一组中的第 个点连通,那么我们可以分以下两种情况讨论:
- 如果点 只与第一组中的第 个点连通,那么 可以从 或者 转移而来,其中 表示异或运算;
- 如果点 与第一组中的第 个点以及其他点都连通,那么 可以从 转移而来。
在上述两种情况中,我们需要选择转移值最小的那个,即有:
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是第一组和第二组中的点数。
class Solution:
def connectTwoGroups(self, cost: List[List[int]]) -> int:
m, n = len(cost), len(cost[0])
f = [[inf] * (1 << n) for _ in range(m + 1)]
f[0][0] = 0
for i in range(1, m + 1):
for j in range(1 << n):
for k in range(n):
if (j >> k & 1) == 0:
continue
c = cost[i - 1][k]
x = min(f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]) + c
f[i][j] = min(f[i][j], x)
return f[m][-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(size1 * 2^size2 * size2), as we process each first-group point and all subsets of second-group points. Space complexity is O(2^size2) if optimizing with a rolling DP array, otherwise O(size1 * 2^size2) for a full DP table. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expecting knowledge of state transition DP with bitmask representation
- question_mark
Looking for correct handling of subsets and connection coverage
- question_mark
Watch for optimization by reducing unnecessary DP updates
常见陷阱
外企场景- error
Forgetting that each second-group point must be connected at least once
- error
Incorrectly updating DP without considering previous masks
- error
Overlooking that multiple first-group points can connect to the same second-group point without extra cost
进阶变体
外企场景- arrow_right_alt
Connection cost matrix may be asymmetric or contain zeros
- arrow_right_alt
Number of points in groups can be equal or have first group larger
- arrow_right_alt
Cost limits can vary, requiring careful handling of maximum sums