给定数字N ,任务是从由前N个自然数形成的集合的所有可能子集中找到所有元素的乘积。
例子:
Input: N = 2
Output: 4
Possible subsets are {{1}, {2}, {1, 2}}.
Product of elements in subsets = {1} * {2} * {1 * 2} = 4
Input: N = 3
Output: 1296
Possible subsets are {{1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}
Product of elements in subsets = 1 * 2 * 3 * (1 * 2) * (1 * 3) * (2 * 3) * (1 * 2 * 3) = 1296
天真的方法:一个简单的解决方案是生成前N个自然数的所有子集。然后,对于每个子集,计算其乘积,最后返回每个子集的整体乘积。
高效方法:
- 可以看出,原始数组的每个元素在所有子集中出现2 (N – 1)次。
- 因此,最终答案中任何元素arr i的贡献将是
i * 2(N – 1)
- 因此,所有子集的多维数据集之和为
12N-1 * 22N-1 * 32N-1......N2N-1
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the product of all elements
// in all subsets in natural numbers from 1 to N
int product(int N)
{
int ans = 1;
int val = pow(2, N - 1);
for (int i = 1; i <= N; i++) {
ans *= pow(i, val);
}
return ans;
}
// Driver Code
int main()
{
int N = 2;
cout << product(N);
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to find the product of all elements
// in all subsets in natural numbers from 1 to N
static int product(int N)
{
int ans = 1;
int val = (int)Math.pow(2, N - 1);
for (int i = 1; i <= N; i++) {
ans *= (int)Math.pow(i, val);
}
return ans;
}
// Driver Code
public static void main (String[] args)
{
int N = 2;
System.out.println(product(N));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to find the product of all elements
# in all subsets in natural numbers from 1 to N
def product(N) :
ans = 1;
val = 2 **(N - 1);
for i in range(1, N + 1) :
ans *= (i**val);
return ans;
# Driver Code
if __name__ == "__main__" :
N = 2;
print(product(N));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG {
// Function to find the product of all elements
// in all subsets in natural numbers from 1 to N
static int product(int N)
{
int ans = 1;
int val = (int)Math.Pow(2, N - 1);
for (int i = 1; i <= N; i++) {
ans *= (int)Math.Pow(i, val);
}
return ans;
}
// Driver Code
public static void Main (string[] args)
{
int N = 2;
Console.WriteLine(product(N));
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
4