Sum of all subsets of a given size ( = K ) | C ++ program for the above approach ; Function to find the sum of all sub - sets of size K ; Frequency of each array element in summation equation . ; calculate factorial of n - 1 ; calculate factorial of k - 1 ; calculate factorial of n - k ; Calculate sum of array . ; Sum of all subsets of size k . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSumOfAllSubsets ( int arr [ ] , int n , int k ) { int factorial_N = 1 , factorial_d = 1 , factorial_D = 1 ; for ( int i = 1 ; i <= n - 1 ; i ++ ) factorial_N *= i ; for ( int i = 1 ; i <= k - 1 ; i ++ ) factorial_d *= i ; for ( int i = 1 ; i <= n - k ; i ++ ) factorial_D *= i ; int freq = factorial_N / ( factorial_d * factorial_D ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; sum = sum * freq ; cout << " Sum ▁ of ▁ all ▁ subsets ▁ of ▁ size ▁ = ▁ " << k << " ▁ is ▁ = > ▁ " << sum << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 5 } ; int n = 4 , k = 2 ; findSumOfAllSubsets ( arr , n , k ) ; return 0 ; }