Given an array with integer 0 to N, how many ways to arrange it such that array[i] cannot be i

非 Y 不嫁゛ 提交于 2019-12-14 03:53:10

问题


Given an array with integer 0 to N, how many ways to arrange it such that at position i of the array, we cannot have i inserted in it?

For example, N = 2

The following arrangements is valid:

  • 1,2,0
  • 2,0,1

Thus, the answer is 2 arrangements

I can't think of a non-brute force method to do this in O(1) time, can anyone help me out?


回答1:


Such kind of permutations is called derangement. Wiki page contains a lot of formulas to count them. For example, recurrence:

!n=(n-1)(!(n-1)+!(n-2))

where !n, known as the subfactorial, represents the number of derangements, with the starting values !0 = 1 and !1 = 0



来源:https://stackoverflow.com/questions/51291851/given-an-array-with-integer-0-to-n-how-many-ways-to-arrange-it-such-that-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!