Leetcode | 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 (ie, for n = 3):

"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

思路是对的,第1个数就是k/(n-1)!,k=k%(n-1)!,第二个数就是k/(n-2)!……

注意这类取余操作得到的是以0开始计数。一开始要把k--。

删除掉一个数之后,需要更新第i个数的值。这里用了一个数组,删掉一个数后,把后面的数往前移。

 1 class Solution {

 2 public:

 3     string getPermutation(int n, int k) {

 4         int a = 1;

 5         vector<int> kth(n); 

 6         

 7         for (int i = 1; i <= n - 1; ++i) {

 8             kth[i - 1] = i;

 9             a *= i;

10         }

11         kth[n - 1] = n;

12         

13         string ret = "";  

14         n--; k--;

15         while (n >= 1) {

16             int v = k / a;                

17             ret += '0' + kth[v];

18             for (int i = v; i < n; ++i) kth[i]=kth[i+1];

19             k = k % a;

20             a = a / n;

21             n--;

22         }

23         ret += '0' + kth[0];

24         

25         return ret;

26     }

27 };

看了网上的代码,再重构了一下.

 1 class Solution {

 2 public:

 3     string getPermutation(int n, int k) {

 4         k--;

 5         int a = 1;

 6         vector<int> kth(n); 

 7         

 8         for (int i = 1; i <= n; ++i) {

 9             kth[i - 1] = i;

10             a *= i;

11         }

12     

13         string ret = "";  

14         for (int i = 0; i < n; ++i) {

15             a = a / (n - i);

16             int v = k / a;

17             k = k % a;

18             ret.push_back(kth[v] + '0');

19             for (int j = v; j < n - i - 1; ++j) kth[j] = kth[j + 1];

20         }

21         

22         return ret;

23     }

24 };

 

你可能感兴趣的:(LeetCode)