中級 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。