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

  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.

» Solve this problem


其实本题数据不大,n最多为9,9! = 362880,枚举应该能够通过(我没试验)。


我采用的方法是计算第k个Permutation。

假设n = 6,k = 400

先计算第一位,

第一位为6,那么它最少也是第5! * 5 + 1个排列,这是因为第一位为1/2/3/4/5时,都有5!个排列,因此第一位为6时,至少是第5! * 5 + 1个排列(这个排列为612345)。

5! * 5 + 1 = 601 > k,所以第一位不可能是6.

一个一个地枚举,直到第一位为4时才行,这时,4xxxxx至少为第5! * 3 + 1 = 361个排列。


然后计算第二位,

与计算第一位时的区别在于,46xxxx至少为第4! * 4 + 1 = 97个排列,这是因为比6小的只有5/3/2/1了。

最后可以计算出第二位为2。


最终得出第400个排列为425361。


根据这个思路,代码如下:

  1. class Solution {  
  2. public:  
  3.     string getPermutation(int n, int k) {  
  4.         // Start typing your C/C++ solution below  
  5.         // DO NOT write int main() function  
  6.         int pow[n + 1];  
  7.         pow[0] = 1, pow[1] = 1;  
  8.         for (int i = 2; i <= n; i++) {  
  9.             pow[i] = pow[i - 1] * i;  
  10.         }  
  11.           
  12.         string ans;  
  13.         bool selected[n + 1];  
  14.         memset(selected, falsesizeof(bool) * (n + 1));  
  15.         for (int i = n; i >= 1; i--) {  
  16.             for (int j = n; j >= 1; j--) {  
  17.                 if (!selected[j]) {  
  18.                     int count = 0;  
  19.                     for (int q = 1; q <= n; q++) {  
  20.                         if (!selected[q] && q < j) {  
  21.                             count++;  
  22.                         }  
  23.                     }                      
  24.                     if (pow[i - 1] * count < k) {  
  25.                         k -= pow[i - 1] * count;  
  26.                         ans += (char) (j + '0');  
  27.                         selected[j] = true;  
  28.                         break;  
  29.                     }  
  30.                 }  
  31.             }  
  32.         }  
  33.           
  34.         return ans;  
  35.     }  
  36. };  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值