给定两个整数N和M ,任务是找到数组对(A,B)的数量,以使数组A和B的大小均为M ,其中A和B的每个项都是1到N之间的整数。对于1和M之间的每个i , A [i]≤B [i] 。还给出了数组A以非降序排序,而数组B以非升序排序。由于答案可能非常大,请以10 9 + 7为模返回答案。
例子:
Input: N = 2, M = 2
Output: 5
1: A= [1, 1] B=[1, 1]
2: A= [1, 1] B=[1, 2]
3: A= [1, 1] B=[2, 2]
4: A= [1, 2] B=[2, 2]
5: A= [2, 2] B=[2, 2]
Input: N = 5, M = 3
Output: 210
方法:请注意,如果存在一对有效的数组A和B,并且B在A之后连接,则结果数组将始终是大小为2 * M的升序或非降序数组。(A + B)将在1到N之间(不必使用1到N之间的所有元素)。现在,这可以简单地将给定问题转换为找到大小为2 * M的所有可能组合,其中每个元素在1到N之间(允许重复),其公式为2 * M + N – 1 C N – 1或(2 * M + N – 1)! /((2 * M)!*(N – 1)!)。
下面是上述方法的实现:
CPP
// C++ code of above approach
#include
#define mod 1000000007
using namespace std;
long long fact(long long n)
{
if(n == 1)
return 1;
else
return (fact(n - 1) * n) % mod;
}
// Function to return the count of pairs
long long countPairs(int m, int n)
{
long long ans = fact(2 * m + n - 1) /
(fact(n - 1) * fact(2 * m));
return (ans % mod);
}
// Driver code
int main()
{
int n = 5, m = 3;
cout << (countPairs(m, n));
return 0;
}
// This code is contributed by mohit kumar 29
Java
// Java code of above approach
class GFG
{
final static long mod = 1000000007 ;
static long fact(long n)
{
if(n == 1)
return 1;
else
return (fact(n - 1) * n) % mod;
}
// Function to return the count of pairs
static long countPairs(int m, int n)
{
long ans = fact(2 * m + n - 1) /
(fact(n - 1) * fact(2 * m));
return (ans % mod);
}
// Driver code
public static void main (String[] args)
{
int n = 5, m = 3;
System.out.println(countPairs(m, n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
from math import factorial as fact
# Function to return the count of pairs
def countPairs(m, n):
ans = fact(2 * m + n-1)//(fact(n-1)*fact(2 * m))
return (ans %(10**9 + 7))
# Driver code
n, m = 5, 3
print(countPairs(m, n))
C#
// C# code of above approach
using System;
class GFG
{
static long mod = 1000000007 ;
static long fact(long n)
{
if(n == 1)
return 1;
else
return (fact(n - 1) * n) % mod;
}
// Function to return the count of pairs
static long countPairs(int m, int n)
{
long ans = fact(2 * m + n - 1) /
(fact(n - 1) * fact(2 * m));
return (ans % mod);
}
// Driver code
public static void Main()
{
int n = 5, m = 3;
Console.WriteLine(countPairs(m, n));
}
}
// This code is contributed by AnkitRai01
输出:
210