📜  给定数组的所有可能的非空子集的值的乘积

📅  最后修改于: 2021-04-23 18:26:22             🧑  作者: Mango

给定大小为N的数组。任务是查找给定数组的所有可能的非空子集的值的乘积。
例子:

方法:经过仔细观察,可以推断出所有子集中每个元素的出现次数为2 N-1 。因此,在最终产品中,数组的每个元素都将自身乘以2 N-1倍。

Product = a[0]2N-1*a[1]2N-1********a[N-1]2N-1

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to find product of all elements
// in all subsets
int product(int a[], int n)
{
    int ans = 1;
    int val = pow(2, n - 1);
     
    for (int i = 0; i < n; i++) {
        ans *= pow(a[i], val);
    }
     
    return ans;
}
 
// Driver Code
int main()
{
    int n = 2;
    int a[] = { 3, 7 };
     
    cout << product(a, n);
     
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
     
    // Function to find product of all elements
    // in all subsets
    static int product(int a[], int n)
    {
        int ans = 1;
        int val = (int)Math.pow(2, n - 1);
         
        for (int i = 0; i < n; i++)
        {
            ans *= (int)Math.pow(a[i], val);
        }
        return ans;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int n = 2;
        int a[] = { 3, 7 };
         
        System.out.println(product(a, n));
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
 
# Function to find product of
# all elements in all subsets
def product(a, n):
    ans = 1
    val = pow(2, n - 1)
 
 
    for i in range(n):
        ans *= pow(a[i], val)
 
    return ans
 
# Driver Code
n = 2
a = [3, 7]
 
print(product(a, n))
 
# This code is contributed by mohit kumar


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to find product of all elements
    // in all subsets
    static int product(int []a, int n)
    {
        int ans = 1;
        int val = (int)Math.Pow(2, n - 1);
         
        for (int i = 0; i < n; i++)
        {
            ans *= (int)Math.Pow(a[i], val);
        }
        return ans;
    }
     
    // Driver Code
    public static void Main ()
    {
        int n = 2;
        int []a = { 3, 7 };
         
        Console.WriteLine(product(a, n));
    }
}
 
// This code is contributed by anuj_67..


Javascript


输出:
441

时间复杂度: O(N)