leetcode[60]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.

class Solution {

public:

string getPermutation(int n, int k) 

{

    k--;

    string str="";

    int data[10]={1};

    int flag[10]={0};

    for (int i=1;i<=n;i++)

    {

        data[i]=data[i-1]*i;

    }

    for (int i=n-1;i>=0;i--)

    {

        int k1=k/data[i];

        int k2=k%data[i];

        k1++;

        int jj=0;

        for (int j=0;j<n;j++)

        {

            if (flag[j]==0)

            {

                jj++;

                if (jj==k1)

                {

                    char temp='0'+(j+1);

                    str+=temp;

                    flag[j]=1;

                    break;

                }

            }

        }

        k=k2;

    }

    return str;

}

};

 

你可能感兴趣的:(LeetCode)