LeetCode 1066. Campus Bikes II
原题链接在这里:https://leetcode.com/problems/campus-bikes-ii/
题目:
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.
We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized.
The Manhattan distance between two points p1
and p2
is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|
.
Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.
Example 1:
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.
Example 2:
Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
Output: 4
Explanation:
We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4.
Note:
0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000
- All worker and bike locations are distinct.
1 <= workers.length <= bikes.length <= 10
题解:
For each worker, check which is the cloest bike, assign it to the worker. And check the next worker until we hit the end of worker list.
We could use state to record which bike has been used. say 01101 means bike 0, 2, 3 have been used because bit 0, 2, 3 are equal to 1.
Check bike i, if state & (1 << i) != 0, this means the bike i has been taken before.
Otherwise, we use this bike and accumlate the manhattan distance.
DFS state needs workers, worker index, bikes, current state and dp to record state. DFS returns minimum distance sum with current state.
Time Complexity: O(n!). n = bikes.length.
Space: O(1 << n).
AC Java:
1 class Solution { 2 public int assignBikes(int[][] workers, int[][] bikes) { 3 int n = bikes.length; 4 int [] dp = new int[1 << n]; 5 return dfs(workers, 0, bikes, 0, dp); 6 } 7 8 private int dfs(int [][] workers, int workerIndex, int [][] bikes, int state, int [] dp){ 9 if(workerIndex == workers.length){ 10 return 0; 11 } 12 13 if(dp[state] != 0){ 14 return dp[state]; 15 } 16 17 int min = Integer.MAX_VALUE; 18 for(int i = 0; i < bikes.length; i++){ 19 if((state & (1 << i)) == 0){ 20 min = Math.min(min, dist(workers[workerIndex], bikes[i]) + dfs(workers, workerIndex + 1, bikes, state | (1 << i), dp)); 21 } 22 } 23 24 dp[state] = min; 25 return min; 26 } 27 28 private int dist(int [] a, int [] b){ 29 return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); 30 } 31 }
类似Campus Bikes.