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:
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.
We want to find the permutation of [0, 1, …, n-1] that minimizes the given score. Since n is small (n ≤ 14), we can use bitmask DP to try all possible permutations efficiently, always choosing the lexicographically smallest one in case of ties.
classSolution:
deffindPermutation(self, nums: list[int]) -> list[int]:
from math import inf
n = len(nums)
dp = [[inf]*n for _ in range(1<<n)]
par = [[-1]*n for _ in range(1<<n)]
for i in range(n):
dp[1<<i][i] =0for mask in range(1<<n):
for last in range(n):
ifnot (mask & (1<<last)):
continuefor nxt in range(n):
if mask & (1<<nxt):
continue nmask = mask | (1<<nxt)
cost = dp[mask][last] + abs(last - nums[nxt])
if cost < dp[nmask][nxt] or (cost == dp[nmask][nxt] and par[nmask][nxt] > last):
dp[nmask][nxt] = cost
par[nmask][nxt] = last
minv, last = inf, -1for i in range(n):
cost = dp[(1<<n)-1][i] + abs(i - nums[0])
if cost < minv or (cost == minv and i < last):
minv, last = cost, i
perm = [0]*n
mask = (1<<n)-1for i in range(n-1, -1, -1):
perm[i] = last
pl = par[mask][last]
mask ^=1<<last
last = pl
return perm
1
// Omitted due to bitmask DP complexity, feasible for small n only
1
// Omitted due to bitmask DP complexity, feasible for small n only