Все задачи
Средне Решено: 0 Процент решений: 0%

Lexicographic Permutation

Find the k-th arrangement of some distinct characters in dictionary order.

Чему вы научитесь

  • Skip whole blocks of permutations at once
  • Convert a rank to a permutation
  • Work with 0-based and 1-based positions

Условие

Показать перевод

List every arrangement of the characters of s in dictionary order. For "abc" the list is abc, acb, bac, bca, cab, cba. Return the k-th entry, counting from 1. Generating the whole list is too slow for 12 characters (479,001,600 arrangements): each block of arrangements that starts with the same character has (length − 1)! entries, so you can pick one character at a time.

Implement lexicographic_permutation(s, k).

Input

s: Distinct characters in any order.

k: The position in the sorted list, counting from 1.

Output

Return the k-th arrangement as a string. Characters are compared by their character codes, so digits come before uppercase letters, which come before lowercase letters.

Ограничения

1 ≤ s.length ≤ 12; all characters of s are distinct; 1 ≤ k ≤ s.length!

Примеры

Пример 1
Ввод:
s = "abc"
k = 4

Ожидаемый вывод:
expected = "bca"
Ввод:
std::string s = "abc";
long long k = 4;

Ожидаемый вывод:
std::string expected = "bca";
Ввод:
string s = "abc";
long k = 4;

Ожидаемый вывод:
string expected = "bca";

Пояснение

The list is abc, acb, bac, bca, cab, cba, and the fourth is "bca".

Пример 2
Ввод:
s = "312"
k = 1

Ожидаемый вывод:
expected = "123"
Ввод:
std::string s = "312";
long long k = 1;

Ожидаемый вывод:
std::string expected = "123";
Ввод:
string s = "312";
long k = 1;

Ожидаемый вывод:
string expected = "123";

Пояснение

The first arrangement is the characters in sorted order: "123".

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 1

Sort the characters first.

Подсказка 2

Each choice of first character covers (length − 1)! permutations, so dividing k − 1 by that number picks it.

Подсказка 3

Remove the chosen character, keep the remainder, and repeat with the rest.

Ожидаемая сложность

O(n²) time, O(n) extra space

Ссылки

Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.