Tutte le sfide
Facile 0 risolte 0% di accettazione

Binomial Coefficient

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ n ≤ 66

0 ≤ k ≤ 100

Esempi

Esempio 1
Input:
n = 5
k = 2

Output atteso:
expected = 10
Input:
long long n = 5;
long long k = 2;

Output atteso:
long long expected = 10;
Input:
long n = 5;
long k = 2;

Output atteso:
long expected = 10;

Spiegazione

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

Esempio 2
Input:
n = 6
k = 0

Output atteso:
expected = 1
Input:
long long n = 6;
long long k = 0;

Output atteso:
long long expected = 1;
Input:
long n = 6;
long k = 0;

Output atteso:
long expected = 1;

Spiegazione

There is exactly one way to choose nothing: 1.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.