LeetCode60 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.(Medium)

分析:

如果采用next_permutation一个一个找的话会超时,所以考虑直接构造的方式。

k / (n-1)! 表示了当前这一位应该取剩下的备选元素中的第几个元素,然后k 减去这一位布置后占据了多少个在k之前的序列,并且n--, 以此递推下去,可以得到结果。

代码:

 1 class Solution {
 2 private:
 3     int fact(int n) {
 4         int result = 1;
 5         for (int i = 1; i <= n; ++i) {
 6             result *= i;
 7         }
 8         return result;
 9     }
10 public:
11     string getPermutation(int n, int k) {
12         string result;
13         vector<int> init(n);
14         for (int i = 0; i < n; ++i) {
15             init[i] = i + 1;
16         }
17         int i = k - 1, count = n;
18                    
19         while (i >= 0 && count > 0) {
20             int temp = i / fact(count - 1);
21             result += ('0' + init[temp]);
22             i -= ( temp * fact(count - 1));
23             init.erase(init.begin() + temp);
24             count--;
25         }
26         return result;
27     }
28 };

 

 

 

 
posted @ 2016-09-22 21:50  wangxiaobao1114  阅读(155)  评论(0编辑  收藏  举报