Number of ways to pair people
Last Updated :
21 Apr, 2021
Given that there are p people in a party. Each person can either join dance as a single individual or as a pair with any other. The task is to find the number of different ways in which p people can join the dance.
Examples:
Input : p = 3
Output : 4
Let the three people be P1, P2 and P3
Different ways are: {P1, P2, P3}, {{P1, P2}, P3},
{{P1, P3}, P2} and {{P2, P3}, P1}.
Input : p = 2
Output : 2
The groups are: {P1, P2} and {{P1, P2}}.
Approach: The idea is to use dynamic programming to solve this problem. There are two situations: Either the person join dance as single individual or as a pair. For the first case the problem reduces to finding the solution for p-1 people. For the second case, there are p-1 choices to select an individual for pairing and after selecting an individual for pairing the problem reduces to finding solution for p-2 people as two people among p are already paired.
So the formula for dp is:
dp[p] = dp[p-1] + (p-1) * dp[p-2].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findWaysToPair( int p)
{
int dp[p + 1];
dp[1] = 1;
dp[2] = 2;
for ( int i = 3; i <= p; i++) {
dp[i] = dp[i - 1] + (i - 1) * dp[i - 2];
}
return dp[p];
}
int main()
{
int p = 3;
cout << findWaysToPair(p);
return 0;
}
|
Java
class GFG
{
static int findWaysToPair( int p)
{
int dp[] = new int [p + 1 ];
dp[ 1 ] = 1 ;
dp[ 2 ] = 2 ;
for ( int i = 3 ; i <= p; i++)
{
dp[i] = dp[i - 1 ] + (i - 1 ) * dp[i - 2 ];
}
return dp[p];
}
public static void main(String args[])
{
int p = 3 ;
System.out.println(findWaysToPair(p));
}
}
|
Python3
def findWays(p):
dp = [ 0 ] * (p + 1 )
dp[ 1 ] = 1
dp[ 2 ] = 2
for i in range ( 3 , p + 1 ):
dp[i] = (dp[i - 1 ] +
(i - 1 ) * dp[i - 2 ])
return dp[p]
p = 3
print (findWays(p))
|
C#
using System;
class GFG
{
public static int findWaysToPair( int p)
{
int [] dp = new int [p + 1];
dp[1] = 1;
dp[2] = 2;
for ( int i = 3; i <= p; i++)
{
dp[i] = dp[i - 1] + (i - 1) * dp[i - 2];
}
return dp[p];
}
public static void Main( string [] args)
{
int p = 3;
Console.WriteLine(findWaysToPair(p));
}
}
|
PHP
<?php
function findWaysToPair( $p )
{
$dp = array ();
$dp [1] = 1;
$dp [2] = 2;
for ( $i = 3; $i <= $p ; $i ++)
{
$dp [ $i ] = $dp [ $i - 1] +
( $i - 1) * $dp [ $i - 2];
}
return $dp [ $p ];
}
$p = 3;
echo findWaysToPair( $p );
?>
|
Javascript
<script>
function findWaysToPair(p)
{
var dp = Array(p+1);
dp[1] = 1;
dp[2] = 2;
for ( var i = 3; i <= p; i++) {
dp[i] = dp[i - 1] + (i - 1) * dp[i - 2];
}
return dp[p];
}
var p = 3;
document.write( findWaysToPair(p));
</script>
|
Time Complexity: O(p)
Auxiliary Space: O(p)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...