给定数字n,我们需要从由前n个自然数组成的集合的所有可能子集中找到所有元素的总和。
例子 :
Input : n = 2
Output : 6
Possible subsets are {{1}, {2},
{1, 2}}. Sum of elements in subsets
is 1 + 2 + 1 + 2 = 6
Input : n = 3
Output : 24
Possible subsets are {{1}, {2}, {3},
{1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}
Sum of subsets is :
1 + 2 + 3 + (1 + 2) + (1 + 3) +
(2 + 3) + (1 + 2 + 3)
一个简单的解决方案是生成所有子集。对于每个子集,计算其总和,最后返回总和。
一个有效的解决方案基于以下事实:从1到n的每个数字都恰好出现2 (n-1)次。因此,我们所需的总和为(1 + 2 + 3 + .. + n)* 2 (n-1) 。总和可以写成(n *(n + 1)/ 2)* 2 (n-1)
C++
// CPP program to find sum of all subsets
// of a set.
#include
using namespace std;
unsigned long long findSumSubsets(int n)
{
// sum of subsets is (n * (n + 1) / 2) *
// pow(2, n-1)
return (n * (n + 1) / 2) * (1 << (n - 1));
}
int main()
{
int n = 3;
cout << findSumSubsets(n);
return 0;
}
Java
// Java program to find sum of all subsets
// of a set.
class GFG {
static long findSumSubsets(int n)
{
// sum of subsets is (n * (n + 1) / 2) *
// pow(2, n-1)
return (n * (n + 1) / 2) * (1 << (n - 1));
}
// Driver code
public static void main(String[] args)
{
int n = 3;
System.out.print(findSumSubsets(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to find
# sum of all subsets
# of a set.
def findSumSubsets( n):
# sum of subsets
# is (n * (n + 1) / 2) *
# pow(2, n-1)
return (n * (n + 1) / 2) * (1 << (n - 1))
# Driver code
n = 3
print(findSumSubsets(n))
# This code is contributed
# by sunnysingh.
C#
// C# program to find sum of all subsets
// of a set.
using System;
class GFG {
static long findSumSubsets(int n)
{
// sum of subsets is (n * (n + 1) / 2) *
// pow(2, n-1)
return (n * (n + 1) / 2) * (1 << (n - 1));
}
// Driver code
public static void Main()
{
int n = 3;
Console.WriteLine(findSumSubsets(n));
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
24