- 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
- 48 lines of Java from the credited upstream file 3149.java.
- 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 int[] findPermutation(int[] nums) {3 final int n = nums.length;4 int[][] mem = new int[n][1 << n];5 6 7 int[][] bestPick = new int[n][1 << n];8 9 10 getScore(nums, 0, 1, bestPick, mem);11 return construct(bestPick);12 }13 14 15 16 private int getScore(int[] nums, int last, int mask, int[][] bestPick, int[][] mem) {17 if (Integer.bitCount(mask) == nums.length)18 return Math.abs(last - nums[0]); 19 if (mem[last][mask] > 0)20 return mem[last][mask];21 22 int minScore = Integer.MAX_VALUE;23 for (int i = 1; i < nums.length; ++i) {24 if ((mask >> i & 1) == 1)25 continue;26 int nextMinScore = Math.abs(last - nums[i]) + getScore(nums, i, mask | 1 << i, bestPick, mem);27 if (nextMinScore < minScore) {28 minScore = nextMinScore;29 bestPick[last][mask] = i;30 }31 }32 33 return mem[last][mask] = minScore;34 }35 36 private int[] construct(int[][] bestPick) {37 int[] ans = new int[bestPick.length];38 int last = 0;39 int mask = 1;40 for (int i = 0; i < bestPick.length; ++i) {41 ans[i] = last;42 last = bestPick[last][mask];43 mask |= 1 << last;44 }45 return ans;46 }47}48