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.

分析:对于n的排列来说,第一个数字出现的区间是第1个到(n-1)!个排列。用 (k - 1) / (n - 1)! 所得到的index就是第一个数字所在的最小序列(12345……n-1)的下标。将最小序列的index位置上的数字删除。

已经用了(n - 1)!个数字了,那么还剩下k = k - index * (n - 1)!这么多个数。如何确定第二个数字呢?同理,第二个数字出现的区间是之后的1到(n - 2)!个排列。用(k - 1)/ (n - 2)! 所得到的index 就可以确定 第二个数字在 上面已经删除了某些index的最小序列中的位置。

以此类推。

运行时间4ms

 1 class Solution {
 2 public:
 3     string getPermutation(int n, int k) {
 4         string result;
 5         vector<int> base;
 6         for(int i = 0; i < n; i++) base.push_back(i + 1);
 7         
 8         for(int j = n - 1; j >= 0; j--){
 9             int index = (k - 1) / factorial(j);
10             k = k - index * factorial(j);
11             result += '0' + base[index];
12             base.erase(base.begin() + index);
13         }
14         return result;
15     }
16     int factorial(int n){
17         if(n == 0) return 1;
18         else return n * factorial(n - 1);
19     }
20 };

 

posted @ 2015-05-13 16:26  amazingzoe  阅读(108)  评论(0编辑  收藏  举报