Problem:
Given n and k, return the k-th permutation sequence.
Example
For n = 3, all permutations are listed as follows:
"123"
"132"
"213"
"231"
"312"
"321"
If k = 4, the fourth permutation is "231"
Note
n will be between 1 and 9 inclusive.
Challenge
O(n*k) in time complexity is easy, can you do it in O(n^2) or less?
My Solution:
The most intuitive way is calling nextPermuation method for k times. It takes O(k * n);
Assume there are n non-repeated numbers,whose k-th permuation is a1,a2,a3, …, an.
For each increassing of a1, there are (n-1)! possibilities for a2 to an. So a1 = k / (n-1)!;
Similarly we can get the following as following:
k_2 = k % (n-1)!;
a_2 = k_2 / (n-2)!;
...
k_{n-1} = k_{n-2} / 2!;
a_{n-1} = k-{n-1} / 1!;
a_n = 1;
1 | /************************************************************************* |