给定数字N,任务是计算使用相邻元素形成的对的所有可能组合。
注意:如果一个元素对已经存在,则不能在下一个元素对中进行选择。例如:对于{1,2,3}:{1,2}和{2,3}将不被视为正确的组合。
例子:
Input : N = 4
Output : 5
Explanation : If N = 4, the possible combinations are:
{1}, {2}, {3}, {4}
{1, 2}, {3, 4}
{1}, {2, 3}, {4}
{1}, {2}, {3, 4}
{1, 2}, {3}, {4}
Input : N = 5
Output : 8
方法:将问题分解为较小的子问题。如果有N个数字,并且有两种情况,一个数字是单独的,或者是成对的;如果一个数字是单独的,请找出将剩余的(n-1)个数字配对的方法,或者是成对的,找到剩下的配对(n-2)个数字的方式。如果只剩下2个数字,则它们可以单独或成对生成2个组合,如果剩下一个数字,则将是单例,因此只有1个组合。
下面是上述方法的实现:
C++
#include
using namespace std;
// Function to count the number of ways
int ways(int n)
{
// If there is a single number left
// it will form singleton
if (n == 1) {
return 1;
}
// if there are just 2 numbers left,
// they will form a pair
if (n == 2) {
return 2;
}
else {
return ways(n - 1) + ways(n - 2);
}
}
// Driver Code
int main()
{
int n = 5;
cout << "Number of ways = " << ways(n);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG
{
// Function to count the number of ways
static int ways(int n)
{
// If there is a single number left
// it will form singleton
if (n == 1)
{
return 1;
}
// if there are just 2 numbers left,
// they will form a pair
if (n == 2)
{
return 2;
}
else
{
return ways(n - 1) + ways(n - 2);
}
}
// Driver Code
public static void main (String[] args)
{
int n = 5;
System.out.println("Number of ways = " + ways(n));
}
}
Python3
# Python3 code implementation of the above program
# Function to count the number of ways
def ways(n) :
# If there is a single number left
# it will form singleton
if (n == 1) :
return 1;
# if there are just 2 numbers left,
# they will form a pair
if (n == 2) :
return 2;
else :
return ways(n - 1) + ways(n - 2);
# Driver Code
if __name__ == "__main__" :
n = 5;
print("Number of ways = ", ways(n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the above code
using System;
class GFG
{
// Function to count the number of ways
static int ways(int n)
{
// If there is a single number left
// it will form singleton
if (n == 1)
{
return 1;
}
// if there are just 2 numbers left,
// they will form a pair
if (n == 2)
{
return 2;
}
else
{
return ways(n - 1) + ways(n - 2);
}
}
// Driver Code
public static void Main()
{
int n = 5;
Console.WriteLine("Number of ways = " + ways(n));
}
}
// This code is contributed by AnkitRai01
输出:
Number of ways = 8