码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Permutation Sequence

时间:2015-08-15 16:07:34      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

这个字符串的规律就是由小到大的数字序列,第k个字符串就是第k大的数字序列字符串,那么暴力遍历是可行的,但是太慢。

还有个方法就是康托展开,时间复杂度O(n),空间复杂度O(1)。

 1 class Solution {
 2 public:
 3     string getPermutation(int n, int k) {
 4         vector<int> numbers;
 5         for(int i=1;i<=n;i++)
 6         {
 7             numbers.push_back(i);
 8         }
 9         vector<int> result;
10         int b=k-1;
11         for(int i=n-1;i>=0;i--)
12         {
13             int a=b/(jiecheng(i));
14             result.push_back(numbers[a]);
15             numbers.erase(numbers.begin()+a);
16             if(i!=0)
17             {
18                b=b%(jiecheng(i));
19             }
20         }
21         string result_str;
22         for(int i=0;i<result.size();i++)
23         {
24             char ch=result[i]+48;
25             result_str+=ch;
26         }
27         return result_str;
28     }
29     int jiecheng(int n)
30     {
31         int result=1;
32         for(int i=1;i<=n;i++)
33         {
34             result*=i;
35         }
36         return result;
37     }
38 };

 

[LeetCode]Permutation Sequence

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4732527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!