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.

      n=4时,对于“1”,后面的“234”排列数有3!=6个,那么第6个排列为“1432”,第7个排列为“21345”,第12个排列为“2431”,第13个排列为“3124”。

      我们可以直到,对于首数字为“1”的排列,排列在第1~3!之间,对于首数字为"2"的排列,排列在3!+1~2*3!之间,对于首数字为“3”的排列,排列在2*3!+1~3*3!之间....

      于是,对于kth排列,我们从头开始遍历字符串,当后续的个数的阶乘小于或等于k时,则说明当前首数字需要更换为后续一个数字来使当前首数字正确,此时k=k-后续个数的阶乘。循环直到k为0.

       这里,k的初值为k-1,因为字符串的初值即为1th排列。


class Solution {
public:
    int factorial(int n){
        if(n<=1)return 1;
        else return factorial(n-1)*n;
    }
    string getPermutation(int n, int k) {
        string s;
        k--;
        for(int i=1;i<=n;i++)s.push_back(i+'0');
        for(int i=0;i<n-1;i++){
            if(k==0)return s;
            int fact = factorial(n-i-1);
            if(k>=fact){
                int carry=k/fact;
                k=k%fact;
                char temp=s[i+carry];
                for(int j=i+carry-1;j>=i;j--)s[j+1]=s[j];
                s[i]=temp;
            }
        }
        return s;
    }
};

你可能感兴趣的:(LeetCode)