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.
The problem is to give a number n and a number k, and then output the K in a permutation combination of all the numbers of 1-n. The rules are as follows (first change the number behind, that is, four numbers, the first is 1234, the second is 1243)
Then it is easier to think clearly about the problem.
There are a total of n numbers, then each number starts with (n-1)! species, that is, if 1<=k<= (n-1)! Then this combination will start with 1.
After the first number has been determined, then the following number is determined in the same way, on the basis of the first number, with a number (n-2)! species, so it can be inferred that:
When you ask for the K string, the number is determined from the front to the back, and count refers to the number of combinations that begin with a number in the current number.
Public classSolution { PublicString Getpermutation (intNintk) {int[] flag =New int[n]; String result; Char[] ans =New Char[n]; intCount = 1; for(inti = 2;i<n;i++) Count*=i; for(inti = 0;i<n;i++){ if(k = = 1){ for(intj = 0;j<n;j++){ if(Flag[j] = = 0) {Ans[i]= (Char) (j+49); I++; FLAG[J]= 1; } } return NewString (ans); } intnum = (k-1)/count; K= k-num*count; Count= count/(n-1-i); for(intj = 0;j<n;j++){ if(Flag[j] = = 0){ if(num = = 0) {Ans[i]= (Char) (j+49); FLAG[J]= 1; Break; }ElseNum--; } } } return NewString (ans); }}
This problem is a rare time to submit the fastest.
Leetcode permutation Sequence-----java