[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):
"123"
"132"
"213"
"231"
"312"
"321"
Note: Given n will be between 1 and 9 inclusive.
Solution: find the mathematical pattern.
class Solution { public: string getPermutation(int n, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function string ret; int f = 1; for(int i=1; i<n; ++i) f*=i; //f is (n-1)! if(n<=0 || k>f*n || k<1) return ret; vector<int> num(n, 0); //for storing 1, 2, ..., n for(int i=0; i<n; ++i) num[i] = i+1; k--; //convert k-th to (k-1)-th in terms of index int cur = n-1; while(cur>=0){ int index = k/f; ret.push_back(num[index]+'0'); num.erase(num.begin()+index); k=k%f; f = (cur>0?f/cur:1); cur--; } return ret; } };
No comments:
Post a Comment