Similar question https://gateoverflow.in/261274/at-least-one-person-receives-his-her-own-hat
There is a concept called Derangement. Using that,
Number of ways in which N men can be deranged with n hats(say $nD$) = $n! \sum_{k = 0}^{n} \frac{(-1)^{k}}{k!}$
Total number of ways in which n men can pick hats(say $T$) = $n!$
Therefore, $P = \frac{nD}{T} = \sum_{k = 0}^{n} \frac{(-1)^{k}}{k!}$
from sheldon ross.