ปานกลาง 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก