The set [1,2,3,…,n]
contains a total of n! 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.
1 Public classSolution {2 PublicString Getpermutation (intNintk) {3StringBuilder ans =NewStringBuilder ();4StringBuilder tmp =NewStringBuilder ();5 for(inti = 1; i<=n; i++) tmp.append (i);6 intFactor =calculate (n);7 intindex = 0;8 for(inti = n; i>=1; i--){9Factor/=i;Tenindex = (k-1)/factor; One ans.append (Tmp.charat (index)); AK-= index*factor; - Tmp.deletecharat (index); - } the returnans.tostring (); - } - - Public intCalculateintN) { + intsum = 1; - for(;n>=1; n--){ +Sum *=N; A } at returnsum; - } -}
N Number of permutation total has n factorial, based on this property we can get a corresponding number of which is. The idea is that, for example, the current length is n, and we know that each of the same starting elements corresponds (N-1)! A permutation,
That is (n-1)! After a permutation, a starting element is changed. Therefore, as long as the current k is carried out (N-1)! The resulting number is the index of the current remaining array so that the corresponding element can be obtained.
Https://discuss.leetcode.com/topic/17348/explain-like-i-m-five-java-solution-in-o-n
Permutation Sequence Java Solutions