60. Permutation Sequence

Posted Zzz...y

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 kth permutation sequence.

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


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

找出n个数全排列的第k个序列。

解决:n个数全排列,第1~(n-1)!个数,肯定是1打头的。

用一个数组记录一下已经使用过的数字。

 1 class Solution {
 2 public:
 3     int Allper(int n) {
 4         int res = 1;
 5         while (n > 0)
 6             res *= n--;
 7         return res;
 8     }
 9     string getPermutation(int n, int k) {
10         int cnt = 0;
11         vector<int> num(n);
12         string res;
13         int i;
14         int total;
15         while (res.size() < n) {
16             total = Allper(n - res.size() - 1);
17             i = 0;
18             while (i * total + cnt < k)
19                 ++i;
20             cnt += (i - 1) * total;
21             for (int j=0; j<n; ++j) {
22                 if (num[j] == 0)
23                     --i;
24                 if (i == 0) {
25                     num[j] = 1;
26                     res += to_string(j + 1);
27                     break;
28                 }
29             }
30         }
31         return res;
32     }
33 };

 

以上是关于60. Permutation Sequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(60):Permutation Sequence

LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

60. Permutation Sequence

60. Permutation Sequence

Permutation Sequence LT60

60. Permutation Sequence