C# n条水平平行线与m条垂直平行线相交的平行四边形的数量(Number of parallelograms when n horizontal parallel lines intersect m vertical parallel lines)
给定两个正整数n和m。任务是计算 n 条水平平行线与 m 条垂直平行线相交可以形成任意大小的平行四边形的数量。
例子:
输入:n = 3, m = 2
输出:3
2个尺寸为 1x1 的平行四边形和 1 个尺寸为 2x1 的平行四边形。
输入:n = 5, m = 5
输出:100
这个想法是使用组合,即从给定的 n 个项目中选择 k 个项目的方式数由n C r,表示如图:给出。
要形成平行四边形,我们需要两条水平平行线和两条垂直平行线。因此,选择两条水平平行线的方式数为n C 2,表示如图:,选择两条垂直平行线的方式数为m C 2,表示如图:
。因此,可能的平行四边形总数为n C 2 x m C 2,表示如图:
。
以下是此方法的实现:
// C# Program to find number of parallelogram when
// n horizontal parallel lines intersect m vertical
// parallel lines.
using System;
class GFG
{
static int MAX = 10;
// Find value of Binomial Coefficient
static void binomialCoeff(int [,]C, int n, int k)
{
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= Math.Min(i, k); j++)
{
// Base Cases
if (j == 0 || j == i)
C[i, j] = 1;
// Calculate value using previously
// stored values
else
C[i, j] = C[i - 1, j - 1] + C[i - 1, j];
}
}
}
// Return number of parallelogram when n horizontal
// parallel lines intersect m vertical parallel lines.
static int countParallelogram(int n, int m)
{
int [,]C = new int[MAX, MAX];
binomialCoeff(C, Math.Max(n, m), 2);
return C[n, 2] * C[m, 2];
}
// Driver code
public static void Main()
{
int n = 5, m = 5;
Console.WriteLine(countParallelogram(n, m));
}
}
// This code is contributed By vt_m.
输出:
100
时间复杂度: O(n 2 ) ,如图:
辅助空间: O(n 2 ),如图:
使用基础数学
同样的问题可以通过使用基本数学来解决,因为我们知道n C 2 = n*(n-1)/2, m C 2,表示如图: 也是如此,所以只需使用基本数学,我们就可以在 O(1) 中解决这个问题
以下是上述方法的实现:
using System;
class GFG {
// This method calculates the number of parallelograms
// that can be formed given the dimensions n and m,
// where n and m are the number of rows and columns.
public static int FindTheParallelogram(int n, int m)
{
// Calculate nC2 = (n * (n - 1)) / 2
// This formula represents the number of ways to
// choose 2 items from n. For a parallelogram, we
// need to choose 2 rows from n and 2 columns from
// m.
int result
= ((n * (n - 1)) / 2) * ((m * (m - 1)) / 2);
return result;
}
}
class Program {
static void Main(string[] args)
{
int n = 5;
int m = 5;
// Calculate and display the number of
// parallelograms that can be formed with the given
// dimensions n and m.
Console.WriteLine("Number of Parallelograms: "
+ GFG.FindTheParallelogram(n, m));
}
}
输出:
100
时间复杂度:O(1)
空间复杂度:O(1)
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。