📜  使用给定长度的 Array 计数可能的子数组和子序列

📅  最后修改于: 2021-09-04 11:48:04             🧑  作者: Mango

给定一个表示数组长度的整数N ,任务是计算给定数组长度下可能的子数组和子序列的数量。
例子:

方法:子数组计数的关键观察事实是数组的每个索引元素可能的结束位置数可以是(N – i),因此对于大小为N的数组的子数组计数可以是:

Count of Sub-arrays = (N) * (N + 1)
                     ---------------
                            2

可能的子序列计数的关键观察事实是数组的每个元素是否可以包含在子序列中。因此,每个元素的选择为 2。

Count of subsequences = 2N

下面是上述方法的实现:

C++
// C++ implementation to count
// the subarray and subsequence of
// given length of the array
#include 
using namespace std;
 
// Function to count the subarray
// for the given array
int countSubarray(int n){
    return ((n)*(n + 1))/2;
}
 
// Function to count the subsequence
// for the given array length
int countSubsequence(int n){
    return pow(2, n);
}
 
// Driver Code
int main()
{
    int n = 5;
    cout << (countSubarray(n)) << endl;
    cout << (countSubsequence(n)) << endl;
    return 0;
}
 
// This code is contributed by mohit kumar 29


Java
// Java implementation to count
// the subarray and subsequence of
// given length of the array
class GFG{
  
// Function to count the subarray
// for the given array
static int countSubarray(int n){
    return ((n)*(n + 1))/2;
}
  
// Function to count the subsequence
// for the given array length
static int countSubsequence(int n){
    return (int) Math.pow(2, n);
}
  
// Driver Code
public static void main(String[] args)
{
    int n = 5;
    System.out.print((countSubarray(n)) +"\n");
    System.out.print((countSubsequence(n)) +"\n");
}
}
  
// This code is contributed by Princi Singh


Python
# Python implementation to count
# the subarray and subsequence of
# given length of the array
 
# Function to count the subarray
# for the given array
def countSubarray(n):
    return ((n)*(n + 1))//2
     
# Function to count the subsequence
# for the given array length
def countSubsequence(n):
    return (2**n)
 
# Driver Code   
if __name__ == "__main__":
    n = 5
    print(countSubarray(n))
    print(countSubsequence(n))


C#
// C# implementation to count
// the subarray and subsequence of
// given length of the array
using System;
 
class GFG{
   
// Function to count the subarray
// for the given array
static int countSubarray(int n){
    return ((n)*(n + 1))/2;
}
   
// Function to count the subsequence
// for the given array length
static int countSubsequence(int n){
    return (int) Math.Pow(2, n);
}
   
// Driver Code
public static void Main(String[] args)
{
    int n = 5;
    Console.Write((countSubarray(n)) +"\n");
    Console.Write((countSubsequence(n)) +"\n");
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
15
32

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live