#3149
Find the Minimum Cost Array Permutation
HardArrayDynamic ProgrammingBit ManipulationBitmaskDynamic ProgrammingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n * 2^n) |
| Space | O(n) | O(n * 2^n) |
💡
Intuition
Time O(n * 2^n)Space O(n * 2^n)
The optimal solution uses dynamic programming to efficiently calculate the minimum score by leveraging the cyclic nature of the problem. By fixing one element (e.g., perm[0] = 0), we can reduce the complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Fix perm[0] = 0 to ensure the lexicographically smallest permutation.
- 2Step 2: Use dynamic programming with bit masking to represent subsets of the remaining elements.
- 3Step 3: Recursively calculate the minimum score for each subset and store results to avoid redundant calculations.
solution.py19 lines
1def min_cost_permutation(nums):
2 n = len(nums)
3 dp = [[float('inf')] * n for _ in range(1 << n)]
4 dp[1][0] = 0
5 for mask in range(1 << n):
6 for i in range(n):
7 if mask & (1 << i):
8 for j in range(n):
9 if not (mask & (1 << j)):
10 new_mask = mask | (1 << j)
11 dp[new_mask][j] = min(dp[new_mask][j], dp[mask][i] + abs(j - nums[i]))
12 min_score = float('inf')
13 best_perm = []
14 for i in range(1, n):
15 score = dp[(1 << n) - 1][i] + abs(i - nums[0])
16 if score < min_score:
17 min_score = score
18 best_perm = [0] + [j for j in range(1, n) if (1 << j) & (1 << i)]
19 return best_permℹ
Complexity note: The time complexity is O(n * 2^n) due to the dynamic programming approach that explores all subsets of the elements, while the space complexity is O(n * 2^n) for storing the DP table.
- 1Fixing one element helps reduce the search space significantly.
- 2Using dynamic programming allows us to avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.