求所有子序列之和
给定一个包含n 个整数的数组。任务是找到数组的每个子序列的总和。
例子 :
Input : arr[] = { 6, 8, 5 }
Output : 76
All subsequence sum are:
{ 6 }, sum = 6
{ 8 }, sum = 8
{ 5 }, sum = 5
{ 6, 8 }, sum = 14
{ 6, 5 }, sum = 11
{ 8, 5 }, sum = 13
{ 6, 8, 5 }, sum = 19
Total sum = 76.
Input : arr[] = {1, 2}
Output : 6
方法1(蛮力):
生成所有子序列,求每个子序列之和。
方法2(高效方法):
对于大小为 n 的数组,我们总共有 2^n 个子序列(包括空的)。观察,总共 2 n个子序列,每个元素出现 2 n-1次。
例如,arr[] = { 5, 6, 7 }
因此,所有子序列的总和将是 (所有元素的总和) * 2 n-1 。
下面是这种方法的实现:
C++
// C++ program to find sum of all sub-sequences
// of an array.
#include
using namespace std;
// Return sum of sum of all sub-sequence.
int sum(int arr[], int n)
{
int ans = 0;
// Finding sum of the array.
for (int i = 0; i < n; i++)
ans += arr[i];
return ans * pow(2, n - 1);
}
// Driver Code
int main()
{
int arr[] = { 6, 7, 8 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << sum(arr, n) << endl;
return 0;
}
Java
// Java program to find sum of
// all sub-sequences of an array.
import java.io.*;
import java.math.*;
class GFG {
// Return sum of sum of all sub-sequence.
static int sum(int arr[], int n)
{
int ans = 0;
// Finding sum of the array.
for (int i = 0; i < n; i++)
ans += arr[i];
return ans * (int)(Math.pow(2, n - 1));
}
// Driver Code
public static void main(String args[])
{
int arr[]= { 6, 7, 8 };
int n = arr.length;
System.out.println(sum(arr, n));
}
}
// This code is contributed by Nikita Tiwari.
Python3
# Python 3 program to find sum of
# all sub-sequences of an array.
# Return sum of sum of all sub-sequence.
def sm(arr , n) :
ans = 0
# Finding sum of the array.
for i in range(0, n) :
ans = ans + arr[i]
return ans * pow(2, n - 1)
# Driver Code
arr = [ 6, 7, 8 ]
n=len(arr)
print(sm(arr, n))
# This code is contributed by Nikita Tiwari.
C#
// C# program to find sum of
// all sub-sequences of an array.
using System;
class GFG
{
// Return sum of sum of all sub-sequence.
static int sum(int []arr, int n)
{
int ans = 0;
// Finding sum of the array.
for (int i = 0; i < n; i++)
ans += arr[i];
return ans * (int)(Math.Pow(2, n - 1));
}
// Driver Code
public static void Main()
{
int []arr= { 6, 7, 8 };
int n = arr.Length;
Console.Write(sum(arr, n));
}
}
// This code is contributed by nitin mittal
PHP
Javascript
输出:
84