Number of distinct subsets of a set
Last Updated :
02 Aug, 2022
Given an array of n distinct elements, count total number of subsets.
Examples:
Input : {1, 2, 3}
Output : 8
Explanation:
the array contain total 3 element.its subset
are {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {3, 1}, {1, 2, 3}.
so the output is 8..
We know number of subsets of set of size n is 2n
How does this formula work?
For every element, we have two choices, we either pick it or do not pick it. So in total we have 2 * 2 * … (n times) choices which is 2n
Alternate explanation is :
- Number of subsets of size 0 = nC0
- Number of subsets of size 1 = nC1
- Number of subsets of size 2 = nC2
- ………………..
- Total number of subsets = nC0 + nC1 + nC2 + …. + nCn = 2n
Please refer Sum of Binomial Coefficients for details.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int subsetCount( int arr[], int n)
{
return 1 << n;
}
int main()
{
int A[] = { 1, 2, 3 };
int n = sizeof (A) / sizeof (A[0]);
cout << subsetCount(A, n);
return 0;
}
|
Java
class GFG {
static int subsetCount( int arr[], int n)
{
return 1 << n;
}
public static void main(String[] args)
{
int A[] = { 1 , 2 , 3 };
int n = A.length;
System.out.println(subsetCount(A, n));
}
}
|
Python3
import math
def subsetCount(arr, n):
return 1 << n
A = [ 1 , 2 , 3 ]
n = len (A)
print (subsetCount(A, n))
|
C#
using System;
class GFG {
static int subsetCount( int []arr, int n)
{
return 1 << n;
}
public static void Main()
{
int []A = { 1, 2, 3 };
int n = A.Length;
Console.WriteLine(subsetCount(A, n));
}
}
|
PHP
<?php
function subsetCount( $arr , $n )
{
return 1 << $n ;
}
$A = array ( 1, 2, 3 );
$n = sizeof( $A );
echo (subsetCount( $A , $n ));
?>
|
Javascript
<script>
function subsetCount(arr, n)
{
return 1 << n;
}
let A = [ 1, 2, 3 ];
let n = A.length;
document.write(subsetCount(A, n));
</script>
|
Share your thoughts in the comments
Please Login to comment...