Background
The Listen&Say Test will be hold on May 11, so I decided to fill my blog
with English words until that day.
Problem
There goes a problem.
You’ve got 2 intergers N,k. Please calculate the kth permutation of ∀k∈[i,n].
Solution
It’s easy to know that we can got it by Depth-first Search, but its Time complexity is O(n!).
DeCantor Expansion is a algorithm which can solve problems like these calculating the kth permutationin O(nlogn) with heap optimization.
Let’s explain how it works in a simple example. Set N=5,k=61, the answer is a[].
1.Let 61 / 4! = 2 ... 13, it shows that there’re 2 numbers behind a[1] are smaller than a[1].
Therefore, a[1]=3;
2.Let 13 / 3! = 2 ... 1, it shows that there’re 2 numbers behind a[2] are smaller than a[2].
Therefore, a[2]=4;
3.Let 1 / 2! = 0 ... 1, it shows that there’re 0 number behind a[3] are smaller than a[3].
Therefore, a[3]=1;
4.Let 1 / 1! = 1 ... 0, it shows that there’re 1 number behind a[4] are smaller than a[4].
Therefore, a[4]=5;
Therefore, a[5]=2,a[]={3,4,1,5,2}.
Summary
∀i∈[1,n−1], let k / (n−1)!, the answer you’ve got is the number of interger j∈[i+1,n] which has a[j]<a[i]. And let k equals to the remainder.
The End
Reference material