 GeeksforGeeks App
Open App Browser
Continue

# Counting pairs when a person can form pair with at most one

Consider a coding competition on geeksforgeeks practice. Now there are n distinct participants taking part in the competition. A single participant can make pair with at most one other participant. We need count the number of ways in which n participants participating in the coding competition.

Examples :

```Input : n = 2
Output : 2
2 shows that either both participant
can pair themselves in one way or both
of them can remain single.

Input : n = 3
Output : 4
One way : Three participants remain single
Three More Ways : [(1, 2)(3)], [(1), (2,3)]
and [(1,3)(2)]```

Method 1:

1) Every participant can either pair with another participant or can remain single.
2) Let us consider X-th participant, he can either remain single or he can pair up with someone from [1, x-1].

Below is the implementation of the above idea:

## C++

 `// Number of ways in which participant can take part.``#include``using` `namespace` `std;` `int` `numberOfWays(``int` `x)``{``    ``// Base condition``    ``if` `(x==0 || x==1)    ``        ``return` `1;` `    ``// A participant can choose to consider``    ``// (1) Remains single. Number of people``    ``//     reduce to (x-1)``    ``// (2) Pairs with one of the (x-1) others.``    ``//     For every pairing, number of people``    ``//     reduce to (x-2).``    ``else``        ``return` `numberOfWays(x-1) +``               ``(x-1)*numberOfWays(x-2);``}` `// Driver code``int` `main()``{``    ``int` `x = 3;``    ``cout << numberOfWays(x) << endl;``    ``return` `0;``}`

## Java

 `// Number of ways in which``// participant can take part.``import` `java.io.*;` `class` `GFG {` `static` `int` `numberOfWays(``int` `x)``{``    ``// Base condition``    ``if` `(x==``0` `|| x==``1``)    ``        ``return` `1``;` `    ``// A participant can choose to consider``    ``// (1) Remains single. Number of people``    ``//     reduce to (x-1)``    ``// (2) Pairs with one of the (x-1) others.``    ``//     For every pairing, number of people``    ``//     reduce to (x-2).``    ``else``        ``return` `numberOfWays(x-``1``) +``            ``(x-``1``)*numberOfWays(x-``2``);``}` `// Driver code``public` `static` `void` `main (String[] args) {``int` `x = ``3``;``System.out.println( numberOfWays(x));``    ` `    ``}``}` `// This code is contributed by vt_m.`

## Python3

 `# Python program to find Number of ways``# in which participant can take part.` `# Function to calculate number of ways.``def` `numberOfWays (x):` `    ``# Base condition``    ``if` `x ``=``=` `0` `or` `x ``=``=` `1``:``        ``return` `1``        ` `    ``# A participant can choose to consider``    ``# (1) Remains single. Number of people``    ``# reduce to (x-1)``    ``# (2) Pairs with one of the (x-1) others.``    ``# For every pairing, number of people``    ``# reduce to (x-2).``    ``else``:``        ``return` `(numberOfWays(x``-``1``) ``+``              ``(x``-``1``) ``*` `numberOfWays(x``-``2``))` `# Driver code``x ``=` `3``print` `(numberOfWays(x))` `# This code is contributed by "Sharad_Bhardwaj"`

## C#

 `// Number of ways in which``// participant can take part.``using` `System;` `class` `GFG {` `    ``static` `int` `numberOfWays(``int` `x)``    ``{``        ` `        ``// Base condition``        ``if` `(x == 0 || x == 1)``            ``return` `1;``    ` `        ``// A participant can choose to``        ``// consider (1) Remains single.``        ``// Number of people reduce to``        ``// (x-1) (2) Pairs with one of``        ``// the (x-1) others. For every``        ``// pairing, number of people``        ``// reduce to (x-2).``        ``else``            ``return` `numberOfWays(x - 1) +``            ``(x - 1) * numberOfWays(x - 2);``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `Main ()``    ``{``        ``int` `x = 3;``        ` `        ``Console.WriteLine(numberOfWays(x));``    ``}``}` `// This code is contributed by vt_m.`

## PHP

 ``

## Javascript

 ``

Output

`4`

Time Complexity: O(2x)
Auxiliary Space: O(log(x)), due to recursive call stack

Since there are overlapping subproblems, we can optimize it using dynamic programming

## C++

 `// Number of ways in which participant can take part.``#include``using` `namespace` `std;` `int` `numberOfWays(``int` `x)``{``    ``int` `dp[x+1];``    ``dp = dp = 1;` `    ``for` `(``int` `i=2; i<=x; i++)``       ``dp[i] = dp[i-1] + (i-1)*dp[i-2];` `    ``return` `dp[x];``}` `// Driver code``int` `main()``{``    ``int` `x = 3;``    ``cout << numberOfWays(x) << endl;``    ``return` `0;``}`

## Java

 `// Number of ways in which``// participant can take part.``import` `java.io.*;``class` `GFG {` `static` `int` `numberOfWays(``int` `x)``{``    ``int` `dp[] = ``new` `int``[x+``1``];``    ``dp[``0``] = dp[``1``] = ``1``;` `    ``for` `(``int` `i=``2``; i<=x; i++)``    ``dp[i] = dp[i-``1``] + (i-``1``)*dp[i-``2``];` `    ``return` `dp[x];``}` `// Driver code``public` `static` `void` `main (String[] args) {``int` `x = ``3``;``System.out.println(numberOfWays(x));``    ` `    ``}``}``// This code is contributed by vipinyadav15799`

## Python3

 `# Python program to find Number of ways``# in which participant can take part.` `# Function to calculate number of ways.``def` `numberOfWays (x):` `    ``dp``=``[]``    ``dp.append(``1``)``    ``dp.append(``1``)``    ``for` `i ``in` `range``(``2``,x``+``1``):``        ``dp.append(dp[i``-``1``]``+``(i``-``1``)``*``dp[i``-``2``])``    ``return``(dp[x])``    `  `# Driver code``x ``=` `3``print` `(numberOfWays(x))` `# This code is contributed by "Sharad_Bhardwaj"`

## C#

 `// Number of ways in which``// participant can take part.``using` `System;` `class` `GFG {` `    ``static` `int` `numberOfWays(``int` `x)``    ``{``        ``int` `[]dp = ``new` `int``[x+1];``        ``dp = dp = 1;``    ` `        ``for` `(``int` `i = 2; i <= x; i++)``            ``dp[i] = dp[i - 1] +``                 ``(i - 1) * dp[i - 2];``    ` `        ``return` `dp[x];``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `Main ()``    ``{``        ``int` `x = 3;``        ` `        ``Console.WriteLine(numberOfWays(x));``    ``}``}` `// This code is contributed by vt_m. `

## PHP

 ``

## Javascript

 ``

Output

`4`

Time Complexity : O( x )
Auxiliary Space: O( x )

Efficient approach: Space optimization O(1)

In previous approach we the current value dp[i] is only depend upon the previous 2 values i.e. dp[i-1] and dp[i-2]. So to optimize the space we can keep track of previous and current values by the help of three variables prev1, prev2 and curr which will reduce the space complexity from O(x) to O(1).

Implementation Steps:

• Create 2 variables prev1 and prev2 to keep track o previous values of DP.
• Initialize base case prev1 = prev2 = 1.
• Create a variable curr to store current value.
• Iterate over subproblem using loop and update curr.
• After every iteration update prev1 and prev2 for further iterations.
• At last return curr.

Implementation:

## C++

 `// C++ code for above approach` `#include ``using` `namespace` `std;` `// function to find the Number of``// ways in which participant can take part.``int` `numberOfWays(``int` `x)``{` `    ``// current value``    ``int` `curr;` `    ``// to keep track of previous values``    ``int` `prev1 = 1, prev2 = 1;` `    ``// iterate to get current values``    ``// from previousyl stored values.``    ``for` `(``int` `i = 2; i <= x; i++) {``        ``curr = prev2 + (i - 1) * prev1;` `        ``// assigning values to iterate further``        ``prev1 = prev2;``        ``prev2 = curr;``    ``}` `    ``// return final answer``    ``return` `curr;``}` `// Driver code``int` `main()``{``    ``int` `x = 3;``    ``cout << numberOfWays(x) << endl;``    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `Main {``  ``public` `static` `int` `numberOfWays(``int` `x)``  ``{``    ``// current value``    ``int` `curr = ``0``;` `    ``// to keep track of previous values``    ``int` `prev1 = ``1``, prev2 = ``1``;` `    ``// iterate to get current values``    ``// from previously stored values.``    ``for` `(``int` `i = ``2``; i <= x; i++) {``      ``curr = prev2 + (i - ``1``) * prev1;` `      ``// assigning values to iterate further``      ``prev1 = prev2;``      ``prev2 = curr;``    ``}` `    ``// return final answer``    ``return` `curr;``  ``}` `  ``public` `static` `void` `main(String[] args)``  ``{``    ``int` `x = ``3``;``    ``System.out.println(numberOfWays(x));``  ``}``}`

## Python3

 `# function to find the Number of``# ways in which participant can take part.`  `def` `numberOfWays(x):``    ``# current value``    ``curr ``=` `0` `    ``# to keep track of previous values``    ``prev1, prev2 ``=` `1``, ``1` `    ``# iterate to get current values``    ``# from previously stored values.``    ``for` `i ``in` `range``(``2``, x``+``1``):``        ``curr ``=` `prev2 ``+` `(i``-``1``)``*``prev1` `        ``# assigning values to iterate further``        ``prev1, prev2 ``=` `prev2, curr` `    ``# return final answer``    ``return` `curr`  `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ``x ``=` `3``    ``print``(numberOfWays(x))`

## Javascript

 `function` `numberOfWays(x) {``// current value``    ``let curr = 0;``    ` `    ``// to keep track of previous values``    ``let prev1 = 1,``        ``prev2 = 1;``        ` `        ` `     ``// iterate to get current values``    ``// from previously stored values.``    ``for` `(let i = 2; i <= x; i++) {``        ``curr = prev2 + (i - 1) * prev1;``        ``prev1 = prev2;``        ``prev2 = curr;``    ``}``// return final answer``    ``return` `curr;``}` `let x = 3;``console.log(numberOfWays(x));`

Output

`4`

Time Complexity : O( x )
Auxiliary Space: O( 1 )

This article is contributed by nikunj_agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.