Problème
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.
Contraintes
0 ≤ n ≤ 66
0 ≤ k ≤ 100
Exemples
Entrée :
n = 5
k = 2
Sortie attendue :
expected = 10
Entrée :
long long n = 5;
long long k = 2;
Sortie attendue :
long long expected = 10;
Entrée :
long n = 5;
long k = 2;
Sortie attendue :
long expected = 10;
Explication
The pairs from 5 items number 5 × 4 / 2 = 10.
Entrée :
n = 6
k = 0
Sortie attendue :
expected = 1
Entrée :
long long n = 6;
long long k = 0;
Sortie attendue :
long long expected = 1;
Entrée :
long n = 6;
long k = 0;
Sortie attendue :
long expected = 1;
Explication
There is exactly one way to choose nothing: 1.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Factorials of numbers above 20 do not fit in 64 bits, so avoid them.
Indice 2
One row of Pascal's triangle can be updated in place from right to left.
Indice 3
C(n, k) equals C(n, n − k), and it is 0 when k > n.
Complexité attendue
O(n · k) time, O(k) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.