LeetCode //C - 60. Permutation Sequence

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:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the k t h k^{th} kth permutation sequence.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

Example 3:

Input: n = 3, k = 1
Output: ""123"

Constraints:
  • 1 <= n <= 9
  • 1 <= k <= n!

From: LeetCode

Link: 60. Permutation Sequence


Solution:

Ideas:
  1. Factorial Calculation: The function starts by calculating factorials, which helps in determining which block or set of permutations the desired permutation falls into.
  2. 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.
  3. 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.
  4. 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:
c 复制代码
// 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;
}
相关推荐
格林威6 分钟前
Baumer相机金属焊缝缺陷识别:提升焊接质量检测可靠性的 7 个关键技术,附 OpenCV+Halcon 实战代码!
人工智能·数码相机·opencv·算法·计算机视觉·视觉检测·堡盟相机
你撅嘴真丑31 分钟前
第八章 - 贪心法
开发语言·c++·算法
VT.馒头36 分钟前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
wanghu202437 分钟前
AT_abc443_C~E题题解
c语言·算法
梵刹古音41 分钟前
【C语言】 浮点型(实型)变量
c语言·开发语言·嵌入式
u0109272711 小时前
模板元编程调试方法
开发语言·c++·算法
2401_838472511 小时前
C++图形编程(OpenGL)
开发语言·c++·算法
-dzk-1 小时前
【代码随想录】LC 203.移除链表元素
c语言·数据结构·c++·算法·链表
进击的小头2 小时前
陷波器实现(针对性滤除特定频率噪声)
c语言·python·算法
知无不研2 小时前
冒泡排序算法
算法·冒泡排序·排序