問題
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
例
入力:
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.
入力:
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 つずつ開いてみましょう。
ヒント 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用に調整されています。上記の説明と制約に従ってください。