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):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
代码:
1 string getPermutation(int n, int k) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int fac[10]; 5 fac[0] = 1; 6 for(int i = 1; i <= 9; i++){ 7 fac[i] = fac[i-1]*i; 8 } 9 string result = ""; 10 vector<int> nums; 11 for(int i = 0; i < n; i++) 12 nums.push_back(i+1); 13 for(int i = n; i >= 1; i--){ 14 if(k <= fac[i-1]){ 15 result += (nums[0]+'0'); 16 nums.erase(nums.begin()); 17 } 18 else if(k == fac[i]){ 19 for(vector<int>::iterator it = nums.end()-1; it >= nums.begin(); it--){ 20 result += (*it+'0'); 21 } 22 break; 23 } 24 else{ 25 int j = (k-1)/fac[i-1]+1; 26 k = k - (j-1)*fac[i-1]; 27 vector<int>::iterator it = nums.begin(); 28 while(j > 1){ 29 it++; 30 j--; 31 } 32 result += (*it+'0'); 33 nums.erase(it); 34 } 35 } 36 return result; 37 }