Moyen 0 résolus 0 % de réussite

Derangements

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

0 ≤ n ≤ 20

Exemples

Exemple 1
Entrée :
n = 3

Sortie attendue :
expected = 2
Entrée :
long long n = 3;

Sortie attendue :
long long expected = 2;
Entrée :
long n = 3;

Sortie attendue :
long expected = 2;

Explication

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

Exemple 2
Entrée :
n = 4

Sortie attendue :
expected = 9
Entrée :
long long n = 4;

Sortie attendue :
long long expected = 9;
Entrée :
long n = 4;

Sortie attendue :
long expected = 9;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

Only the last two values are needed at any time.

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.