Java implementation LeetCode 60 arranged in the k-th

60. The arrangement of the k-th

Given set [1,2,3, ..., n], a total of all the elements n! Permutations.

Arranged in order of size lists all cases, and 11 markers, when when n 3 =, all arranged as follows:

"123"
"132"
"213"
"231"
"312"
"321"
for a given n and k, returns the k-th order.

Description:

Given n ranges [1, 9].
K is given range [1, n!].
Example 1:

Input: n = 3, k = 3
Output: "213"
Example 2:

Input: n = 4, k = 9
Output: "2314"

PS:
directly to do with backtracking, then we need to go back to the k-th termination of the arrangement would not be out of time, but the efficiency is still moving
can use mathematical methods to solve, because the numbers are successive natural numbers from the beginning of 1, the arrangement appears order can be pushed
calculated, for n = 4, k = 15 k = process found 15 arranged:

    1 + 对2,3,4的全排列 (3!个)         
    2 + 对1,3,4的全排列 (3!个)         3, 1 + 对2,4的全排列(2!个)
    3 + 对1,2,4的全排列 (3!个)-------> 3, 2 + 对1,4的全排列(2!个)-------> 3, 2, 1 + 对4的全排列(1!个)-------> 3214
    4 + 对1,2,3的全排列 (3!个)         3, 4 + 对1,2的全排列(2!个)         3, 2, 4 + 对1的全排列(1!个)
    
    确定第一位:
        k = 14(从0开始计数)
        index = k / (n-1)! = 2, 说明第15个数的第一位是3 
        更新k
        k = k - index*(n-1)! = 2
    确定第二位:
        k = 2
        index = k / (n-2)! = 1, 说明第15个数的第二位是2
        更新k
        k = k - index*(n-2)! = 0
    确定第三位:
        k = 0
        index = k / (n-3)! = 0, 说明第15个数的第三位是1
        更新k
        k = k - index*(n-3)! = 0
    确定第四位:
        k = 0
        index = k / (n-4)! = 0, 说明第15个数的第四位是4
    最终确定n=4时第15个数为3214 
class Solution {
    public String getPermutation(int n, int k) {
 
     
        
        StringBuilder sb = new StringBuilder();
        // 候选数字
        List<Integer> candidates = new ArrayList<>();
        // 分母的阶乘数
        int[] factorials = new int[n+1];
        factorials[0] = 1;
        int fact = 1;
        for(int i = 1; i <= n; ++i) {
            candidates.add(i);
            fact *= i;
            factorials[i] = fact;
        }
        k -= 1;
        for(int i = n-1; i >= 0; --i) {
            // 计算候选数字的index
            int index = k / factorials[i];
            sb.append(candidates.remove(index));
            k -= index*factorials[i];
        }
        return sb.toString();
    }
}
Released 1174 original articles · won praise 10000 + · views 500 000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104335405