- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 33 lines of C++ from the credited upstream file 1066.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {4 vector<int> mem(1 << bikes.size(), INT_MAX);5 return assignBikes(workers, bikes, 0, 0, mem);6 }7 8 private:9 10 11 int assignBikes(const vector<vector<int>>& workers,12 const vector<vector<int>>& bikes, int workerIndex, int used,13 vector<int>& mem) {14 if (workerIndex == workers.size())15 return 0;16 if (mem[used] != INT_MAX)17 return mem[used];18 19 for (int bikeIndex = 0; bikeIndex < bikes.size(); ++bikeIndex)20 if ((used >> bikeIndex & 1) == 0)21 mem[used] =22 min(mem[used], dist(workers[workerIndex], bikes[bikeIndex]) +23 assignBikes(workers, bikes, workerIndex + 1,24 used | 1 << bikeIndex, mem));25 26 return mem[used];27 }28 29 int dist(const vector<int>& p1, const vector<int>& p2) {30 return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]);31 }32};33