The set By listing and labeling all of the permutations in order,
Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. |
One straightforward solution would be to call the next_permutation and count the calling times, but it is not necessary to do the actual permutation, we just need to find out which digit in which position. Here is the idea. For each k, divide the number of previous permutations into some factorials, for each factorial, count how many and save this info into an index array. Based on this array, we can choose which digit at each position. e.g, for n=4, k=20, it has 19 permutations before, 19 = 33! + 02! + 1*1! + 0, so the index[] would be 0,1,0,3 (reversing order), which can be interpreted as the order of digit in an ordered array, e.g, 3 means arr[3] in [1,2,3,4] which is 4.
|
|
|
|
|