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

Binomial Coefficient

Count the ways to choose k items out of n (n choose k).

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

  • Compute combinations without factorials
  • Apply Pascal's rule
  • Handle k greater than n

โจทย์

ดูฉบับแปล

The binomial coefficient C(n, k), read "n choose k", is the number of ways to pick k items from n different items when order does not matter. The formula n! / (k! (n − k)!) overflows quickly if you compute the factorials first, so build the answer step by step or use Pascal's rule C(n, k) = C(n − 1, k − 1) + C(n − 1, k).

Implement binomial_coefficient(n, k).

Input

n: The number of items.

k: How many to choose.

Output

Return C(n, k). If k > n there is no way to choose, so return 0.

เงื่อนไข

0 ≤ n ≤ 66

0 ≤ k ≤ 100

ตัวอย่าง

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

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

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

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

คำอธิบาย

The pairs from 5 items number 5 × 4 / 2 = 10.

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

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

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

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

คำอธิบาย

There is exactly one way to choose nothing: 1.

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

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

คำใบ้ 1

Factorials of numbers above 20 do not fit in 64 bits, so avoid them.

คำใบ้ 2

One row of Pascal's triangle can be updated in place from right to left.

คำใบ้ 3

C(n, k) equals C(n, n − k), and it is 0 when k > n.

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

O(n · k) time, O(k) extra space

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

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

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

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

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

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

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