60. Permutation Sequence LeetCode] [k-th arrangement (Medium) (JAVA)

60. Permutation Sequence LeetCode] [k-th arrangement (Medium) (JAVA)

Topic Address: https://leetcode.com/problems/permutation-sequence/

Subject description:

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:

1. "123"
2. "132"
3. "213"
4. "231"
5. "312"
6. "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"

Subject to the effect

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

Problem-solving approach

From the k-th starting arrangement 1 is first started from 0 k - 1 Species

In fact, as long as the n-th element is calculated to
1, k / (n - 1 )! Can be calculated n-th element
2, the cycle of each element is calculated

class Solution {
    public String getPermutation(int n, int k) {
        if (n == 1 && k == 1) return "1";
        List<Integer> list = new ArrayList<>();
        int product = 1;
        for (int i = 1; i <= n; i++) {
            list.add(i);
            if (i != n) product *= i;
        }
        k--;
        StringBuilder res = new StringBuilder();

        while (list.size() > 0) {
            int cur = k / product;
            res.append(list.remove(cur));
            k = k % product;
            product /= Math.max(1, list.size());
        }

        return res.toString();
    }
}

When execution: 2 ms, beat the 81.25% of all users to submit in Java
memory consumption: 37.6 MB, beat the 5.78% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2278

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104800050
Recommended