MediumNo. 1066LeetCode Premium
Campus Bikes II — LeetCode 1066 Python Solution
- Pattern
- Backtracking
- Topics
- Bit Manipulation, Array, Dynamic Programming, Backtracking, Bitmask
- Reading time
- 3 min
- Source
- leetcode.com
The problem
On a campus represented as a 2D grid, there are n workers and m bikes, with n <= m. Each worker and bike is a 2D coordinate on this grid.
Example
- Input
- workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
- Output
- 6
- Explanation
- We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6.
Python solution
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int:
n, m = len(workers), len(bikes)
f = [[inf] * (1 << m) for _ in range(n + 1)]
f[0][0] = 0
for i, (x1, y1) in enumerate(workers, 1):
for j in range(1 << m):
for k, (x2, y2) in enumerate(bikes):
if j >> k & 1:
f[i][j] = min(
f[i][j],
f[i - 1][j ^ (1 << k)] + abs(x1 - x2) + abs(y1 - y2),
)
return min(f[n])Complexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1066. Campus Bikes II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0473 | Matchsticks to Square | Medium |
| 0526 | Beautiful Arrangement | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 1655 | Distribute Repeating Integers | Hard |
| 1723 | Find Minimum Time to Finish All Jobs | Hard |
Frequently asked questions
- How hard is LeetCode 1066. Campus Bikes II?
LeetCode 1066. Campus Bikes II is rated Medium on LeetCode.
- What topics does LeetCode 1066. Campus Bikes II cover?
LeetCode 1066. Campus Bikes II is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.
- Is LeetCode 1066. Campus Bikes II a premium problem?
Yes. LeetCode 1066. Campus Bikes II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.