[LeetCode] Find the Derangement of An Array 找数组的错排
In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position.
There's originally an array consisting of n integers from 1 to n in ascending order, you need to find the number of derangement it can generate.
Also, since the answer may be very large, you should return the output mod 109 + 7.
Example 1:
Input: 3
Output: 2
Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
Note:n is in the range of [1, 106].
这道题给了我们一个数组,让我们求其错排的个数,所谓错排就是1到n中的每个数字都不在其原有的位置上,全部打乱了,问能有多少种错排的方式。博主注意到了这道题又让对一个很大的数取余,而且每次那个很大的数都是109 + 7,为啥大家都偏爱这个数呢,有啥特别之处吗?根据博主之前的经验,这种结果很大很大的题十有八九都是用dp来做的,那么就建一个一维的dp数组吧,其中dp[i]表示1到i中的错位排列的个数。那么难点就是找递推公式啦,先从最简单的情况来看:
n = 1 时有 0 种错排
n = 2 时有 1 种错排 [2, 1]
n = 3 时有 2 种错排 [3, 1, 2], [2, 3, 1]
然后博主就在想知道了dp[2],能求出dp[3]吗,又在考虑是不是算加入数字3的情况的个数。结果左看右看发现没有啥特别的规律,又在想是不是有啥隐含的信息需要挖掘,还是没想出来。于是看了一眼标签,发现是Math,我的天,难道又是小学奥数的题?挣扎了半天最后还是放弃了,上网去搜大神们的解法。其实这道题是组合数学种的错排问题,是有专门的递归公式的。
我们来想n = 4时该怎么求,我们假设把4排在了第k位,这里我们就让k = 3吧,那么我们就把4放到了3的位置,变成了:
x x 4 x
我们看被4占了位置的3,应该放到哪里,这里分两种情况,如果3放到了4的位置,那么有:
x x 4 3
那么此时4和3的位置都确定了,实际上只用排1和2了,那么就相当于只排1和2,就是dp[2]的值,是已知的。那么再来看第二种情况,3不在4的位置,那么此时我们把4去掉的话,就又变成了:
x x x
这里3不能放在第3个x的位置,在去掉4之前,这里是移动4之前的4的位置,那么实际上这又变成了排1,2,3的情况了,就是dp[3]的值。
再回到最开始我们选k的时候,我们当时选了k = 3,其实k可以等于1,2,3,也就是有三种情况,所以dp[4] = 3 * (dp[3] + dp[2])。
那么递推公式也就出来了:
dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2])
有了递推公式,代码就不难写了吧,参见代码如下:
解法一:
class Solution {
public:
int findDerangement(int n) {
if (n < ) return ;
vector<long long> dp(n + , );
dp[] = ; dp[] = ;
for (int i = ; i <= n; ++i) {
dp[i] = (dp[i - ] + dp[i - ]) * (i - ) % ;
}
return dp[n];
}
};
下面这种解法精简了空间,因为当前值只跟前两个值有关系,所以没必要保留整个数组,只用两个变量来记录前两个值,并每次更新一下就好了,参见代码如下:
解法二:
class Solution {
public:
int findDerangement(int n) {
long long a = , b = , res = ;
for (int i = ; i <= n; ++i) {
res = (i - ) * (a + b) % ;
a = b;
b = res;
}
return (n == ) ? : res;
}
};
下面这种方法是对之前的递推公式进行了推导变形,使其只跟前一个数有关,具体的推导步骤是这样的:
我们假设 e[i] = dp[i] - i * dp[i - 1]
递推公式为: dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2])
将递推公式带入假设,得到:
e[i] = -dp[i - 1] + (n - 1) * dp[i - 2] = -e[i - 1]
从而得到 e[i] = (-1)^n
那么带回假设公式,可得: dp[i] = i * dp[i - 1] + (-1)^n
根据这个新的递推公式,可以写出代码如下:
解法三:
class Solution {
public:
int findDerangement(int n) {
long long res = ;
for (int i = ; i <= n; ++i) {
res = (i * res + (i % == ? : -)) % ;
}
return res;
}
};
参考资料:
https://discuss.leetcode.com/topic/94429/o-n-short-java-code
https://discuss.leetcode.com/topic/94767/java-dp-solution-with-explanation
https://discuss.leetcode.com/topic/94421/java-solution-with-explanation-by-using-staggered-formula
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Find the Derangement of An Array 找数组的错排的更多相关文章
- [LeetCode] Find All Duplicates in an Array 找出数组中所有重复项
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others ...
- [LeetCode] Single Element in a Sorted Array 有序数组中的单独元素
Given a sorted array consisting of only integers where every element appears twice except for one el ...
- [LeetCode] Peak Index in a Mountain Array 山形数组的顶峰坐标
Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists som ...
- LeetCode 977. Squares of a Sorted Array (有序数组的平方)
题目标签:Array 题目给了我们一组 从小到大的 integers,让我们平方数字 并且 也排序成 从小到达. 因为有负数在里面,平方后,负数在array的位置会变动. 可以设left 和 righ ...
- [LeetCode] 26. Remove Duplicates from Sorted Array 有序数组中去除重复项
Given a sorted array nums, remove the duplicates in-place such that each element appear only once an ...
- leetCode 26.Remove Duplicates from Sorted Array(删除数组反复点) 解题思路和方法
Remove Duplicates from Sorted Array Given a sorted array, remove the duplicates in place such that e ...
- [leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)
Given a sorted array nums, remove the duplicates in-place such that each element appear only once an ...
- [LeetCode] 80. Remove Duplicates from Sorted Array II 有序数组中去除重复项 II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twic ...
- [leetcode]81. Search in Rotated Sorted Array II旋转过有序数组里找目标值II(有重)
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. 思路 ...
随机推荐
- 转载---SuperMap GIS 9D SP1学习视频播单
转自:http://blog.csdn.net/supermapsupport/article/details/79219102 SuperMap GIS 9D SP1学习视频播单 我们一直在思考什么 ...
- 第十四,十五周PTA作业
1.第十四周part1 7-3 #include<stdio.h> int main() { int n; scanf("%d",&n); int a[n]; ...
- 火车头采集器对接织梦cms图集发布时, 采集网上图片超时的解决方法
背景介绍: 火车头采集器对接织梦cms图片集发布时, 对于多张(超过30张)大图片时, 经常会出现图集发布超时的情况. 问题分析: 因为php对于资源的处理有默认的超时时间30秒, 而我尝试了好多方 ...
- 14-TypeScript简单工厂模式
在TypeScript中,要调用功能,通常在调用方通过实例化被调用方对象来调用相关方法,但这种实现在调用方和被调用方形成了强耦合的关系. 另外如果被调用方有种实现,在调用方需要根据场景去实例化不同的类 ...
- python之路--day6--字符编码
一.知识储备 cpu--控制和运算 内存--暂时存储cpu需要的数据 硬盘--永久保存数据2.文本编辑器的原理存储原理 1,启动文本编辑器 2,在编辑器上输入内容---此时输入内容还在内存上 3,保存 ...
- 九、Python发送QQ邮件(SMTP)
看了廖雪峰老师的教程: 一封电子邮件的旅程就是 发件人 -> MUA -> MTA -> MTA -> 若干个MTA -> MDA <- MUA <- 收件人 ...
- maven安装、配置
maven的安装和配置 1.将maven解压到自定义文件夹下.例如解压到如下目录(解压目录最好不要有中文字): 2:配置环境变量:一定要注意要用分号:与其他值隔开 3.在cmd中测试,验证是否安装成 ...
- angular2 学习笔记 ( unit test 单元测试 )
第一次写单元测试. 以前一直都有听说 TDD 的事情. 今天总算是去尝试了一下. 先说说 TDD 的想法, 是这样的, 开发项目的流程 : 确定需求 -> 写类,接口,方法的名字(不写具体实现代 ...
- api-gateway实践(05)新网关工作 - 缓存定义
一.缓存分类 1.服务注册信息 1.1.[GroupCode_VersionCode]对应[Version定义]的缓存 缓存类型:hash ...
- express学习(三)—— cookie和session
express学习(三)-- cookie和session cookie存在浏览器中,最大只能保存4K数据,不安全 session存在服务器中,不能独立(先读取cookie再读取session),较安 ...