Permutation Sequence

来源:互联网 发布:电信80端口 编辑:程序博客网 时间:2024/06/02 06:26
-----QUESTION-----

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.

-----SOLUTION-----

class Solution {public:    string getPermutation(int n, int k) {        string result = "";        bool hasUsed[n+1]; //whether the number has used in the string        for(int i = 0; i<=n; i++)        {            hasUsed[i] = false;        }        int dp[n]; //permutation number of a digit with i width        dp[0] = 1;        dp[1] = 1;        for(int i = 2; i< n; i++)        {            dp[i] = i* dp[i-1];        }                int num;        stringstream ss;        string str;                for(int i = n; i>0; i--)        {            num = k/dp[i-1];            if(k%dp[i-1] != 0) num+=1;            int counter = 0;            int j;            for(j = 1; j<=n && counter!=num; j++)            {                if(!hasUsed[j])counter++;                if(counter == num) break;            }            hasUsed[j] = true;            ss.clear();             ss<<j;            ss>>str;            result = result +str;            k = k-(num-1)*dp[i-1];        }        return result;    }};


0 0
原创粉丝点击