数组的所有子序列的总和
给定一个包含 n 个整数的数组。求一个数组所有可能子序列的总和。
例子 :
Input : arr[] = { 1, 2 }
Output : 6
All possible subsequences are {}, {1}, {2}
and { 1, 2 }
Input : arr[] = { 1, 2, 3 }
Output : 24
我们已经在下面的帖子中讨论了两种不同的解决方案。
所有子数组的总和 |设置 1
在这篇文章中讨论了一个不同的解决方案。让我们仔细看看这个问题并尝试找到一个模式
Let a[] = { 1, 2, 3 }
All subsequences are {}, {1}, {2}, {3}, {1, 2},
{1, 3}, {2, 3}, {1, 2, 3}
So sum of subsequences are 0 + 1 + 2 + 3 + 3 +
4 + 5 + 6 = 24
Here we can observe that in sum every elements
occurs 4 times. Or in general every element
will occur 2^(n-1) times. And we can also
observe that sum of array elements is 6. So
final result will be 6*4.
一般来说,我们可以通过将数组的所有元素相加乘以 2 (n-1)来找到所有子序列的总和,其中 n 是数组中的元素数。
C++
// CPP program to find sum of
// all subarrays of array
#include
using namespace std;
// To find sum of all subsequences
int findSum(int arr[], int n)
{
// Sum all array elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Result is sum * 2^(n-1)
return sum * (1 << (n - 1));
}
// Driver program to test findSum()
int main()
{
int arr[] = { 1, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findSum(arr, n);
return 0;
}
Java
// Java program to find sum of
// all subarrays of array
public class Main {
// To find sum of all subsequences
static int findSum(int arr[], int n)
{
// Sum all array elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Result is sum * 2^(n-1)
return sum * (1 << (n - 1));
}
// Driver program to test findSum()
public static void main(String[] args)
{
int arr[] = { 1, 2 };
int n = arr.length;
System.out.print(findSum(arr, n));
}
}
Python
# Python program to find sum of
# all subarrays of array
# To find sum of all subsequences
def findSum(arr, n):
# Sum all array elements
sum = 0
for i in range(n):
sum += arr[i]
# Result is sum * 2^(n-1)
return sum * (1 << (n - 1))
# Driver program to test findSum()
arr = [1, 2]
n = len(arr)
print findSum(arr, n)
# This code is submitted by Sachin Bisht
C#
// C# program to find sum of
// all subarrays of array
using System;
class GFG
{
// To find sum of all subsequences
static int findSum(int []arr, int n)
{
// Sum all array elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Result is sum * 2^(n-1)
return sum * (1 << (n - 1));
}
// Driver Code
static public void Main ()
{
int []arr = { 1, 2 };
int n = arr.Length;
Console.WriteLine(findSum(arr, n));
}
}
// This code is contributed by ajit
PHP
Javascript
输出 :
6