【LeetCode】Permutation Sequence

来源:互联网 发布:表情包 知乎 编辑:程序博客网 时间:2024/04/29 12:09

题目描述:

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):

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

Given n and k, return the kth permutation sequence.

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

总觉的这题目我的思路有点绕……若以“1234……n”为第一个序列,那么一个序列的序号是由尾部变动的位数来决定的,以n=4为例,第一个序列为“1234”,只变动最后一位,则最多到1!,变动倒数第二位,则最多到2!=2,倒数第三位则变动到3!=6号序列,由此我们可以将前面顺序部分的个数求出来。

下一步就是确定后面每一位的数字。对倒数第i位,令m = k / i!,s="1234",则swap( s[n-i], n-i+1+m ),为了保持交换后序列还是按升序排列的,我们将它依次换过去,则m+1次交换。

还是以1234为例:

      0  1  2  3

1、1  2  3  4  

2、1  2  4  3

3、1  3  2  4

4、1  3  4  2

5、1  4  2  3

6、1  4  3  2

当k=3时,通过前面第一步我们可以确定第一位是不需要改变的(初始序列为“1234”),然后就该确定s[1]位置的数字,此时i=3,则s[1]的数字每经过(i - 1)!个序列变化一次。令m = k / (i - 1)!=3 / 2 = 1,则s[1]与s[1 + m]=s[2]交换,得到1324,k -= m * (i-1)! =1>=1,则循环终止,否则将k减掉后继续循环。

代码如下:

class Solution {public:string getPermutation(int n, int k) {string ret;for (int i = 1; i <= n; i++)ret += i + '0';int i(0), mult(1);while (mult < k){i++;mult *= i;}if (i)mult /= i;while (k>1){for (int j = 0; j < (k - 1) / mult; j++)swap(ret[n - i], ret[n - i + 1 + j]);k -= (k - 1) / mult*mult;mult /= --i;}return ret;}};


0 0