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 for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
- Given n will be between 1 and 9 inclusive.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
The meaning of problems
1 ~ n has n! Permutations, which are arranged to identify the k-th row of lexicographically.
Thinking
This is a very mathematical problem, what fancy algorithms do not, you have to go to the law of doom
code
1 public String getPermutation(int n, int k) { 2 char[] result = new char[n]; 3 List<Integer> list = new ArrayList<>(); 4 int[] factorial = new int[n]; 5 6 factorial[0] = 1; 7 for (int i = 1; i < n; i++) { 8 factorial[i] = factorial[i-1] *i; 9 } 10 // factorial: 1, 1, 2 11 // denotes the number n corresponding to the full array, and 12 is 13 is for ( int I =. 1; I <= n; I ++ ) { 14 List.add (I); 15 } 16 // usable digital 1-2-3 , with the list because facilitate later delete digital . 17 18 is K--; // pick a high number 19 // starting from the highest bit to the last bit to generate a result 20 is for ( int I = 0; I < n-; I ++ ) { 21 is Result [I] = Character.forDigit is (list.remove (K / factorial [n---I. 1]), 10 ); 22 is K = K% factorial [l--n- I]; 23 is } 24 return new String(result); 25 }