给定N个整数的数组arr [] ,任务是找到给定数组的所有可能的非空子集的值的总和。
例子:
Input: arr[] = {2, 3}
Output: 10
All non-empty subsets are {2}, {3} and {2, 3}
Total sum = 2 + 3 + 2 + 3 = 10
Input: arr[] = {2, 1, 5, 6}
Output: 112
方法:可以观察到,当从所有可能的子集中添加所有元素时,原始数组的每个元素都会出现2 (N – 1)次。这意味着最终答案中任何元素arr [i]的贡献将为arr [i] * 2 (N – 1) 。因此,所需的答案将是(arr [0] + arr [1] + arr [2] +…+ arr [N – 1])* 2 (N – 1) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the required sum
int sum(int arr[], int n)
{
// Find the sum of the array elements
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
// Every element appears 2^(n-1) times
sum = sum * pow(2, n - 1);
return sum;
}
// Driver code
int main()
{
int arr[] = { 2, 1, 5, 6 };
int n = sizeof(arr) / sizeof(int);
cout << sum(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the required sum
static int sum(int arr[], int n)
{
// Find the sum of the array elements
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
}
// Every element appears 2^(n-1) times
sum = sum * (int)Math.pow(2, n - 1);
return sum;
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 2, 1, 5, 6 };
int n = arr.length;
System.out.println(sum(arr, n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to return the required sum
def sum( arr, n):
# Find the sum of the array elements
sum = 0
for i in arr :
sum += i
# Every element appears 2^(n-1) times
sum = sum * pow(2, n - 1)
return sum
# Driver code
arr = [ 2, 1, 5, 6 ]
n = len(arr)
print(sum(arr, n))
# This code is contributed by Arnab Kundu
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the required sum
static int sum(int[] arr, int n)
{
// Find the sum of the array elements
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
}
// Every element appears 2^(n-1) times
sum = sum * (int)Math.Pow(2, n - 1);
return sum;
}
// Driver code
public static void Main ()
{
int[] arr = { 2, 1, 5, 6 };
int n = arr.Length;
Console.WriteLine(sum(arr, n));
}
}
// This code is contributed by CodeMech
Javascript
输出:
112