在 C++ 中找到所有子序列总和的总和
考虑我们有一个有 n 个元素的数组 A。我们必须找到数组中所有子集和的总和。因此,如果数组为 A = [5, 6, 8],则如下所示 −
| 子集 | 和 |
|---|---|
| 5 | 5 |
| 6 | 6 |
| 8 | 8 |
| 5,6 | 11 |
| 6,8 | 14 |
| 5,8 | 13 |
| 5,6,8 | 19 |
| 总和 | 76 |
由于该数组有 n 个元素,那么我们有 2n 个子集(包括空集)。如果仔细观察,我们会发现每个元素出现 2n-1 次
示例
#include<iostream>
#include<cmath>
using namespace std;
int totalSum(int arr[], int n) {
int res = 0;
for (int i = 0; i < n; i++)
res += arr[i];
return res * pow(2, n - 1);
}
int main() {
int arr[] = { 5, 6, 8 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Total sum of the sum of all subsets: " << totalSum(arr, n) << endl;
}输出
Total sum of the sum of all subsets: 76
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP