ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Derangements

Count the arrangements of n items where nothing stays in its original place.

สิ่งที่คุณจะได้เรียนรู้

  • Turn a counting argument into a recurrence
  • Iterate a recurrence from base cases
  • Handle the n = 0 and n = 1 cases

โจทย์

ดูฉบับแปล

Five friends put their hats in a pile and each takes one back at random. In how many ways can it happen that nobody gets their own hat? An arrangement of n items in which no item stays in its original position is called a derangement. The counts start 1, 0, 1, 2, 9, 44 and follow D(n) = (n − 1) × (D(n − 1) + D(n − 2)).

Implement derangements(n).

Input

n: The number of items.

Output

Return the number of derangements of n items. D(0) is 1 (the empty arrangement moves nothing that could stay) and D(1) is 0.

เงื่อนไข

0 ≤ n ≤ 20

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 3

ผลลัพธ์ที่คาดหวัง:
expected = 2
อินพุต:
long long n = 3;

ผลลัพธ์ที่คาดหวัง:
long long expected = 2;
อินพุต:
long n = 3;

ผลลัพธ์ที่คาดหวัง:
long expected = 2;

คำอธิบาย

For items A, B, C only BCA and CAB move every item, so the answer is 2.

ตัวอย่างที่ 2
อินพุต:
n = 4

ผลลัพธ์ที่คาดหวัง:
expected = 9
อินพุต:
long long n = 4;

ผลลัพธ์ที่คาดหวัง:
long long expected = 9;
อินพุต:
long n = 4;

ผลลัพธ์ที่คาดหวัง:
long expected = 9;

คำอธิบาย

D(4) = 3 × (D(3) + D(2)) = 3 × (2 + 1) = 9.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Start from D(0) = 1 and D(1) = 0.

คำใบ้ 2

Each next value uses the two previous ones and the current n.

คำใบ้ 3

Only the last two values are needed at any time.

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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

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

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