LeetCode Permutation Sequence, permutationleetcode
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.
Find the sequence of k.
Train of Thought: we can think of n numbers in a full arrangement of n !, For example, for a certain n, k, such as n = 4, k = 17. First, we know that there are 6, 2, and 1 combinations under n. So 17 = 2*6 + 2*2 + 1,
Because the weight of 6 is a multiple of 2 and there is surplus, the value of the 4th bits (highest bits) is a 1234 small number selected from "3rd", that is, 3;
Since the multiple of the Weight Value 2 is 2 and there is surplus, the value of the 3rd bits is to select a small number of 124 from "3rd", that is, 4;
Since the multiple of the weight value 1 is 1 and there is no surplus, the value of the 2nd bits is to select a small number of 1st from "12", that is, 1;
The last remaining number is appended in reverse order.
class Solution {public: string remove(string s, int index, char &c) { c = s[index-1]; string s1 = s.substr(0, index-1); string s2 = s.substr(index); return s1 + s2; } string getPermutation(int n, int k) { if (n > 9 || n < 1) return ""; string temp = "123456789"; int A[9] = {1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; if (A[n-1] < k) return ""; string s = temp.substr(0, n); if (k == 1) return s; if (k == A[n-1]) { reverse(s.begin(), s.end()); return s; } string ans = ""; char c; for (int i = n-2; i >= 0; i--) { int m = 0; if (k < A[i]) { s = remove(s, 1, c); ans += c; continue; } while (k >= A[i]) { k -= A[i]; m++; } if (k == 0) { s = remove(s, m, c); ans += c; reverse(s.begin(), s.end()); return ans + s; } else { s = remove(s, m+1, c); ans += c; } } return ans; }};