查找C ++中所有子序列的总和
考虑我们有一个包含n个元素的数组A。我们必须找到数组所有子集的总和。因此,如果数组像A=[5,6,8],那么它将像-
由于数组具有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
热门推荐
10 团队文案祝福语简短励志
11 参加婚礼祝福语大全简短
12 生日祝福语大全女孩简短
13 职场祝福语大全 简短精辟
14 结婚祝福语简短精辟 兄弟
15 幼儿狗年祝福语大全简短
16 拜年啦祝福语大全简短
17 婶婶生日贺词简短祝福语
18 孩子16岁祝福语简短