dp
of size n + 1
to store the number of derangements for each number from 0 to n
.dp[0] = 1
and dp[1] = 0
.n
, and for each i
, calculate dp[i]
using the recurrence relation: dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2])
.dp[i]
modulo 1000000007
to prevent integer overflow.dp[n]
as the final answer.