Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
67 lines (51 loc) · 1.54 KB

File metadata and controls

67 lines (51 loc) · 1.54 KB
Copy raw file
Download raw file
Outline
Edit and raw actions

Difficulty: Medium

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"

Solution

Language: Java

class Solution {
    public String getPermutation(int n, int k) {
        int[] factorial = new int[n + 1];
        List<Integer> leftNumList = new ArrayList<>();
        int sum = 1;
        factorial[0] = 1;
        for (int i = 1; i <= n; i++) {
            leftNumList.add(i);
            sum *= i;
            factorial[i] = sum;
        }
        StringBuilder stringBuilder = new StringBuilder();
        k--; // Amazing k--
        for (int i = 1; i <= n; i++) {
            int index = k / factorial[n - i];
            k = k % factorial[n - i];
            stringBuilder.append(leftNumList.get(index));
            leftNumList.remove(index);
        }
        return stringBuilder.toString();
    }
}

Morty Proxy This is a proxified and sanitized view of the page, visit original site.