Find the Minimum Cost Array Permutation Problem
Description
LeetCode Problem 3149.
You are given an array nums which is a permutation of [0, 1, 2, ..., n - 1]. The score of any permutation of [0, 1, 2, ..., n - 1] named perm is defined as:
score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|
Return the permutation perm which has the minimum possible score. If multiple permutations exist with this score, return the one that is lexicographically smallest among them.
Example 1:
Input: nums = [1,0,2]
Output: [0,1,2]
Explanation:

The lexicographically smallest permutation with minimum cost is [0,1,2]. The cost of this permutation is |0 - 0| + |1 - 2| + |2 - 1| = 2.
Example 2:
Input: nums = [0,2,1]
Output: [0,2,1]
Explanation:

The lexicographically smallest permutation with minimum cost is [0,2,1]. The cost of this permutation is |0 - 1| + |2 - 2| + |1 - 0| = 2.
Constraints:
2 <= n == nums.length <= 14numsis a permutation of[0, 1, 2, ..., n - 1].
Solution
Approach: Bitmask DP with Memoization
Shifting a permutation cyclically does not change its score, and we want the lexicographically smallest answer, so it must start with 0.
Since n is at most 14, a bitmask of the numbers already used fits. Let dfs(mask, pre) be the minimum cost still to pay when the used set is mask and the last number placed is pre. If every number is used, the cycle closes and the cost is |pre - nums[0]|. Otherwise try every unused cur and take the minimum of |pre - nums[cur]| + dfs(mask | 1 << cur, cur).
To rebuild the permutation, walk forward from 0. At each step pick the smallest unused cur whose cost equals dfs(mask, pre); trying cur in increasing order gives the lexicographically smallest answer.
Complexity: O(n2 2n) time and O(n 2n) extra space.
from functools import lru_cache
from math import inf
class Solution:
def findPermutation(self, nums: List[int]) -> List[int]:
@lru_cache(None)
def dfs(mask: int, pre: int) -> int:
if mask == (1 << n) - 1:
return abs(pre - nums[0])
res = inf
for cur in range(1, n):
if mask >> cur & 1 ^ 1:
res = min(res, abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur))
return res
def g(mask: int, pre: int):
ans.append(pre)
if mask == (1 << n) - 1:
return
res = dfs(mask, pre)
for cur in range(1, n):
if mask >> cur & 1 ^ 1:
if abs(pre - nums[cur]) + dfs(mask | 1 << cur, cur) == res:
g(mask | 1 << cur, cur)
break
n = len(nums)
ans = []
g(1, 0)
return ans