634. 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].



思路:

dp[n]表示到n能形成的Derangement,dp[n+1]无非是多出来一个数n+1,

(1)n+1可以与0..n之间的任意1个数交换(可以确保没有重复,因为不同的Derangement至少有2位差别,与n+1交换

一位最后还是不同的);

(2)前n位数也不一定严格要求是Derangement,可以存在一位异常,及value等于index,此时等价于dp[n-1]

所以dp[n+1]=n*(dp[n]+dp[n-1])

/*
 * 
 */
public class Solution {
    public int findDerangement(int n) {
    	if(n == 1)	return 0;
    	if(n == 2)	return 1;
    	if(n == 3)	return 2;
    	
        int[] dp = new int[1+n];
        dp[2] = 1;
        dp[3] = 2;
        
        for(int i=4; i<=n; i++) {
        	long t = ((long)dp[i-1] + dp[i-2])*(i-1);
        	dp[i] = (int) (t % (1e9+7));
        }
        
        return (int) (dp[n] % (10e9+7));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值