# 排列序列

给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。

按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:

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

给定 n 和 k,返回第 k 个排列。

 

示例 1:

输入:n = 3, k = 3
输出:
"213"

示例 2:

输入:n = 4, k = 9
输出:
"2314"

示例 3:

输入:n = 3, k = 1
输出:
"123"

 

提示:

以下程序实现了这一功能,请你填补空白处的内容: ```cpp #include #include #include #include static char *getPermutation(int n, int k) { int i; char *result = malloc(n + 1); bool *used = malloc(n * sizeof(bool)); memset(used, false, n * sizeof(bool)); int total = 1; for (i = 1; i <= n; i++) { total *= i; } k = k - 1; for (i = 0; i < n; i++) { total /= (n - i); int gid = k / total; k %= total; int x = -1; int count = 0; ____________________; used[x] = true; result[i] = x + 1 + '0'; } result[n] = '\0'; return result; } int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "Usage: ./test n, k\n"); exit(-1); } printf("%s\n", getPermutation(atoi(argv[1]), atoi(argv[2]))); return 0; } ``` ## template ```cpp #include #include #include #include static char *getPermutation(int n, int k) { int i; char *result = malloc(n + 1); bool *used = malloc(n * sizeof(bool)); memset(used, false, n * sizeof(bool)); int total = 1; for (i = 1; i <= n; i++) { total *= i; } k = k - 1; for (i = 0; i < n; i++) { total /= (n - i); int gid = k / total; k %= total; int x = -1; int count = 0; while (count <= gid) { x = (x + 1) % n; if (!used[x]) { count++; } } used[x] = true; result[i] = x + 1 + '0'; } result[n] = '\0'; return result; } int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "Usage: ./test n, k\n"); exit(-1); } printf("%s\n", getPermutation(atoi(argv[1]), atoi(argv[2]))); return 0; } ``` ## 答案 ```cpp while (count <= gid) { x = (x + 1) % n; if (!used[x]) { count++; } } ``` ## 选项 ### A ```cpp while (count <= gid) { x = (x + 1) % n; if (used[x]) { count++; } } ``` ### B ```cpp while (count < gid) { x = (x + 1) % n; if (used[x]) { count++; } } ``` ### C ```cpp while (count <= gid) { x = x % n; if (used[x]) { count++; } } ```