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 };

 

posted @ 2018-05-09 19:45  Zzz...y  阅读(131)  评论(0编辑  收藏  举报