1 import sys 2 class Solution: 3 def __init__(self): 4 self.sums = sys.maxsize 5 6 def backtrack(self,workers,i,bikes,used,sums): 7 if i == len(workers): 8 self.sums = min(self.sums,sums) 9 return 10 11 if sums > self.sums: 12 return 13 14 for j in range(len(bikes)): 15 if used[j]: 16 continue 17 used[j] = True 18 self.backtrack(workers,i+1,bikes,used,sums+self.getDist(workers[i],bikes[j])) 19 used[j] = False 20 21 def getDist(self,worker,bike): 22 return abs(worker[0]-bike[0]) + abs(worker[1]-bike[1]) 23 24 def assignBikes(self, workers: 'List[List[int]]', bikes: 'List[List[int]]') -> int: 25 v = [False] * len(bikes) 26 self.backtrack(workers,0,bikes,v,0) 27 return self.sums
上面的代码使用回溯法,但是TLE。考虑需要使用动态规划提升效率,目前还做不出来。
看到一个同样思路的解决方案,使用java语言,却可以AC,这难道又是leetcode平台的“语言杀”?
这种同样思路,使用java可以AC,但是使用.net或python却TLE的情况,我是遇到过几次的。
但也有可能是我的代码写的有问题,目前还没弄明白具体原因。
java版本的代码如下:
1 class Solution { 2 public int assignBikes(int[][] workers, int[][] bikes) { 3 dfs(workers, 0, bikes, new boolean[bikes.length], 0); 4 return min; 5 } 6 7 int min = Integer.MAX_VALUE; 8 void dfs(int[][] workers, int i, int[][] bikes, boolean[] used, int sum) { 9 if (i == workers.length) { 10 min = Math.min(min, sum); 11 return; 12 } 13 14 if (sum > min) return; // early termination 15 16 for (int j = 0; j < bikes.length; ++j) { 17 if (used[j]) continue; 18 used[j] = true; 19 dfs(workers, i+1, bikes, used, sum + getDistance(workers[i], bikes[j])); 20 used[j] = false; 21 } 22 } 23 24 int getDistance(int[] worker, int[] bike) { 25 return Math.abs(worker[0] - bike[0]) + Math.abs(worker[1] - bike[1]); 26 } 27 }
参考地址:https://leetcode.com/problems/campus-bikes-ii/discuss/303375/Java-straightforward-DFS-solution