60. Permutation Sequence

来源:互联网 发布:计算圆周率的算法 编辑:程序博客网 时间:2024/05/16 16:59

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,计算n的全排列中第k个排列。

思路:计算,说明这是可以计算的,以1-9为例,以字母1开头的排列的个数是(n-1)!个,那么如果k里包含2个(n-1)!,但是小于3个(n-1)!呢,则这第k个排列一定是以3开头的,同理后边的数字也是这么推的。

class Solution {public:string getPermutation(int n, int k) {vector<int> dp(n+1, 1);for (int i = 2; i <= n; i++){dp[i] = dp[i - 1] * i;}//record n!vector<int> nums(n, 1);for (int i = 0; i < n; i++)nums[i] = i + 1;k = (k-1)%dp[n];string s(n,'1');for (int i = 0; i < n; i++){int index = k / dp[n - 1 - i];s[i] =  nums[index] + '0';nums.erase(nums.begin() + index);k %= dp[n - 1 - i];}return s;}};





0 0
原创粉丝点击