Leetcode Note: Permutation Sequence
I. Description
Assume that {1, 2, 3, 4 ,..., N}, arrange the elements in it. There are n in total! And sort them from small to large. What is the form of the k combination? <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Memory + memory/O94qGjvt/M5cq1z9a/ybLO1dXM4sS/memory + 1xMrHt723qLb + Memory + memory/memory + Memory + 6/memory + Memory = = "brush: java; "> X=an*(n-1)!+an-1*(n-2)!+...+ai*(i-1)!+...+a2*1!+a1*0!
For example:
Question1324
Yes{1,2,3,4}
The number of combinations in the permutation:
First1
, Less1
No, yes0
,0*3!
The second digit is3
, Less3
The number1
And2
,1
It already exists first, so there is only one number2
,1*2!
. The third digit is2
Less2
The number is1
,1
In the first place, so there are0
Number,0*1!
, So1324
Small arrays have0*3!+1*2!+0*1!=2
,1324
Yes3
.
The above is the Cantor encoding process, that isMap a fully ordered ing 1324 to a natural number 3The question is a known natural number.k
The corresponding full arrangement is a decoding process relative to the above steps. The following is a specific example:
How to find out{1,2,3,4,5}
The16
?
1. Use16-1
, Get15
;
2. Use15
Remove4!
, Get0
, Yu15
;
3. Use15
Remove3!
, Get2
, Yu3
;
4. Use3
Remove2!
, Get1
, Yu1
;
5. Use1
Remove 1! , Get1
, Yu0
;
6. Yes0
A smaller number than it is1
So the first priority is1
;
7. Yes2
A smaller number than it is3
,1
It already exists before, so the second is4
;
8. Yes1
A smaller number than it is2
,1
So the third digit is3
;
9. Yes1
A smaller number than it is2
But 1, 3, and 4 have all appeared, so the fourth digit is5
;
10. Based on the above inference, the last number can only be2
;
Therefore{1,4,3,5,2}
.
Based on the above ideas, you can start designing algorithms.
Iii. Sample Code
#include
#include
#include
using namespace std;class Solution{public: string PermutationSequence(int n, int k) { int total = CombinedNumber(n - 1); if (k > total) { cout << The k is larger then the total number of permutation sequence: << total << endl; return Null!; } string a(n, '0'); for (int i = 0; i < n; ++i) a[i] += i + 1; // sorted // Cantor expansion string s = a, result; k--; // (k - 1) values are less than the target value for (int i = n - 1; i > 0; --i) { auto ptr = next(s.begin(), k / total); result.push_back(*ptr); s.erase(ptr); // delete the already used number k %= total; // update the dividend total /= i; // update the divider } result.push_back(s[0]); // The last bit return result; }private: int CombinedNumber(int n) { int num = 1; for (int i = 1; i < n + 1; ++i) num *= i; return num; }};
The following is a simple test code:
#include PermutationSequence.hint main(){ Solution s; int n = 6, k = 150; string result = s.PermutationSequence(n, k); std::cout << n = << n << and the << k << th sequence is: << result << std::endl; getchar(); return 0;}
A correct test result,n = 6
,k = 16
:
Whenk
When the value of exceeds the number of possible combinations: