Narrative description of the problem:
The set [1,2,3,…,n] contains a total ofn! 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 would be between 1 and 9 inclusive.
Basic idea:
According to K and n! , the k sequence should raise several numbers in which position.
Code:
Consider if k > n!? string getpermutation (int n, int k) { //c++ //the first vector<char> base (n, ' 0 '); for (int i = 1; i<=n; i++) base[i-1] = i + ' 0 '; Vector<int> multi (n); int temp = 1; Multi[0] = 1; for (int i =1; i < n; i++) { temp *= i; Multi[i] = temp; } k--; for (int i = 0; i< n-1; i++) { int temp = k/multi[n-i-1]; int pos = i+temp; char C = base[pos]; for (Int J =pos-1; j>=i; j--) base[j+1] = base[j]; Base[i] = C; k = k%multi[n-i-1]; } To string string result = ""; for (int i = 0; i < n; i++) result + = (base[i]); return result; }
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
[Leetcode] Permutation Sequence