Средне Решено: 0 Процент решений: 0%

Derangements

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

Чему вы научитесь

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

Условие

Показать перевод

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.

Ограничения

0 ≤ n ≤ 20

Примеры

Пример 1
Ввод:
n = 3

Ожидаемый вывод:
expected = 2
Ввод:
long long n = 3;

Ожидаемый вывод:
long long expected = 2;
Ввод:
long n = 3;

Ожидаемый вывод:
long expected = 2;

Пояснение

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

Пример 2
Ввод:
n = 4

Ожидаемый вывод:
expected = 9
Ввод:
long long n = 4;

Ожидаемый вывод:
long long expected = 9;
Ввод:
long n = 4;

Ожидаемый вывод:
long expected = 9;

Пояснение

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

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 1

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

Подсказка 2

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

Подсказка 3

Only the last two values are needed at any time.

Ожидаемая сложность

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

Ссылки

Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.