[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.

最开始是暴力算,但是9!实在是太大了,显然超时,后来网上看到大牛们的算法,从前后向后找,已知对于每一次第n位的数字,都有(n-1)!个排列,所以可以根据这个规律直接找到答案。

 1 class Solution {  
 2 public:  
 3     string getPermutation(int n, int k) {
 4         string str;
 5         vector<int> factorial(n + 1, 1);
 6         for (int i = 1; i <= n; ++i) {
 7             str += i + '0';
 8             factorial[i] = factorial[i-1] * i;
 9         }
10         string perm;
11         --k;    // convert to 0-based index
12         for (int i = n - 1; i >= 0; --i) {
13             int quotient = k / factorial[i];
14             perm += str[quotient];
15             str.erase(quotient, 1);
16             k %= factorial[i];
17         }
18         return perm;
19     }
20 }; 

超时的算法:

 1 class Solution {
 2 public:
 3     string getPermutation(int n, int k) {
 4         string str;
 5         for (int i = 1; i <= n; ++i) {
 6             str.push_back('0' + i);
 7         } 
 8         if (n < 2) return str;
 9         
10         int a, b;
11         while (k--) {
12             for (a = n - 2; a >= 0; --a) 
13                 if (str[a] < str[a+1]) 
14                     break;
15             
16             for (b = n - 1; b > a; --b) 
17                 if (str[b] > str[a])
18                     break;
19             
20             swap(str[a], str[b]);
21             reverse(str.begin() + a + 1, str.end());
22         }
23         return str;
24     }
25 };

 

posted @ 2014-04-22 15:41  Eason Liu  阅读(150)  评论(0编辑  收藏  举报