给定一个级别L。任务是找到在给定级别上存在于Pascal三角形中的所有整数的总和。
一个具有6个级别的Pascal三角形如下所示:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
例子:
Input: L = 3
Output: 4
1 + 2 + 1 = 4
Input: L = 2
Output:2
方法:如果我们仔细观察,级别总和的序列将像1、2、4、8、16…一样继续进行。 ,这是GP系列,其中a = 1和r = 2。
因此,Lth级的总和是上述系列中的L’th项。
Lth term = 2L-1
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find sum of numbers at
// Lth level in Pascals Triangle
int sum(int h)
{
return pow(2, h - 1);
}
// Driver Code
int main()
{
int L = 3;
cout << sum(L);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to find sum of numbers at
// Lth level in Pascals Triangle
static int sum(int h)
{
return (int)Math.pow(2, h - 1);
}
// Driver Code
public static void main (String[] args)
{
int L = 3;
System.out.println(sum(L));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the above approach
# Function to find sum of numbers at
# Lth level in Pascals Triangle
def summ(h):
return pow(2, h - 1)
# Driver Code
L = 3
print(summ(L))
# This code is contributed by mohit kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find sum of numbers at
// Lth level in Pascals Triangle
static int sum(int h)
{
return (int)Math.Pow(2, h - 1);
}
// Driver Code
public static void Main ()
{
int L = 3;
Console.WriteLine(sum(L));
}
}
// This code is contributed by anuj_67..
Javascript
输出:
4
时间复杂度: O(1)