#1595
Minimum Cost to Connect Two Groups of Points
HardArrayDynamic ProgrammingBit ManipulationMatrixBitmaskDynamic ProgrammingBitmasking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² * 2^n) | O(n * 2^m * m) |
| Space | O(1) | O(2^m) |
💡
Intuition
Time O(n * 2^m * m)Space O(2^m)
The optimal solution uses dynamic programming with bitmasking to efficiently compute the minimum cost. This approach reduces the number of combinations we need to check by storing intermediate results.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[mask] represents the minimum cost to connect points in the first group represented by 'mask'.
- 2Step 2: Iterate through all possible masks and for each mask, calculate the cost to connect additional points from the second group.
- 3Step 3: Update the DP array with the minimum costs found.
solution.py9 lines
1def minCost(cost):
2 n, m = len(cost), len(cost[0])
3 dp = [float('inf')] * (1 << m)
4 dp[0] = 0
5 for i in range(n):
6 for mask in range((1 << m) - 1, -1, -1):
7 for j in range(m):
8 dp[mask | (1 << j)] = min(dp[mask | (1 << j)], dp[mask] + cost[i][j])
9 return min(dp[(1 << m) - 1], float('inf'))ℹ
Complexity note: This complexity arises because we iterate through all points in the first group (n), and for each point, we check all possible connections to the second group (2^m). This is significantly more efficient than the brute force approach.
- 1Using bitmasking allows us to efficiently track which points are connected.
- 2Dynamic programming helps us avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.