60. Permutation Sequence
The set [1, 2, 3, …, n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
- “123”
- “132”
- “213”
- “231”
- “312”
- “321”
Given n and k, return the k t h k^{th} kth permutation sequence.
Example 1:
Example 2:
Example 3:
Constraints:
- 1 <= n <= 9
- 1 <= k <= n!
From: LeetCode
Link: 60. Permutation Sequence
Solution:
Ideas:
- Factorial Calculation: The function starts by calculating factorials, which helps in determining which block or set of permutations the desired permutation falls into.
- Position Calculation: By dividing k by the factorial of n−1, the function determines the index of the number to place in each position of the resultant string.
- Update and Shift: After determining the position, the selected number is removed from the available list, effectively reducing the problem size for the next iteration.
- Memory Management: The function dynamically allocates memory for the result string and a temporary array to hold available numbers, ensuring to free the temporary memory before returning.
Code:
// Helper function to calculate factorial
int factorial(int x) {
int result = 1;
for (int i = 2; i <= x; i++) {
result *= i;
}
return result;
}
// Function to get the k-th permutation sequence
char* getPermutation(int n, int k) {
int i, j, f;
int len = n;
k--; // Convert k to zero-indexed for easier calculations
// Allocate memory for the result
char *result = malloc((n + 1) * sizeof(char));
result[n] = '\0'; // Null terminate the string
// Create an array to hold numbers 1, 2, 3, ..., n
int *numbers = malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
numbers[i] = i + 1;
}
for (i = 0; i < len; i++) {
f = factorial(n - 1);
j = k / f; // Determine the index of the current digit
result[i] = numbers[j] + '0'; // Set the current position in result
k %= f; // Reduce k
// Remove used number from the array by shifting elements
for (int m = j; m < n - 1; m++) {
numbers[m] = numbers[m + 1];
}
n--;
}
// Clean up and return result
free(numbers);
return result;
}