码迷,mamicode.com
首页 > 其他好文 > 详细

634. Find the Derangement of An Array

时间:2017-11-24 15:01:44      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:cep   app   span   end   asc   solution   code   array   i++   

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].
class Solution {
public:
    int findDerangement(int n) {
        /*
        For ith element, we have switch it with one of the previous numbers 1,2,...,i-1, and for each picked number j, for the positions left except the one take by i, j can take anyone of them. So there are dp[i - 2] permutation if j can take the original position of i, and dp[i - 1] permutations if j can not take the original position of i.
*/
        if(n <= 1) return 0;
        vector<long> dp(n+1);
        long mod = 1000000007;
        dp[2] = 1;
        for(int i = 3; i < dp.size(); i++){
            dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % mod;
        }
        return dp[dp.size() - 1];
    }
};

 

634. Find the Derangement of An Array

标签:cep   app   span   end   asc   solution   code   array   i++   

原文地址:http://www.cnblogs.com/jxr041100/p/7889099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!