- 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
- 52 lines of C++ from the credited upstream file 3149.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks 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 vector<int> findPermutation(vector<int>& nums) {4 const int n = nums.size();5 vector<vector<int>> mem(n, vector<int>(1 << n));6 7 8 vector<vector<int>> bestPick(n, vector<int>(1 << n));9 10 11 getScore(nums, 0, 1, bestPick, mem);12 return construct(bestPick);13 }14 15 private:16 17 18 int getScore(const vector<int>& nums, int last, unsigned mask,19 vector<vector<int>>& bestPick, vector<vector<int>>& mem) {20 if (popcount(mask) == nums.size())21 return abs(last - nums[0]); 22 if (mem[last][mask] > 0)23 return mem[last][mask];24 25 int minScore = INT_MAX;26 for (int i = 1; i < nums.size(); ++i) {27 if (mask >> i & 1)28 continue;29 const int nextMinScore =30 abs(last - nums[i]) + getScore(nums, i, mask | 1 << i, bestPick, mem);31 if (nextMinScore < minScore) {32 minScore = nextMinScore;33 bestPick[last][mask] = i;34 }35 }36 37 return mem[last][mask] = minScore;38 }39 40 vector<int> construct(const vector<vector<int>>& bestPick) {41 vector<int> ans;42 int last = 0;43 int mask = 1;44 for (int i = 0; i < bestPick.size(); ++i) {45 ans.push_back(last);46 last = bestPick[last][mask];47 mask |= 1 << last;48 }49 return ans;50 }51};52