Posts Friends Pairing Problem
Post
Cancel

Friends Pairing Problem

Problem Description

Given N friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up.
Note: Since answer can be very large, return your answer mod 10^9+7.

geeksforgeeks

Solution

snapshot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution
{
    
    long M = 1000000007;
    
    public long countFriendsPairings(int n) 
    { 
        long[] dp = new long[n+1];
        dp[0] = 1;
        dp[1] = 1;
        
        for(int i=2; i<=n; i++){
            dp[i] = (dp[i-1]%M + (i-1)*dp[i-2]%M)%M;
        }        
        
        return dp[n];
        
    }
    
}    
This post is licensed under CC BY 4.0 by the author.