📌  相关文章
📜  集合中不同子集的数量

📅  最后修改于: 2021-05-07 00:40:15             🧑  作者: Mango

给定n个不同元素的数组,计算子集的总数。
例子:

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..

我们知道大小为n的集合的子集数为2 n
这个公式如何运作?
对于每个元素,我们都有两个选择,我们要么选择它,要么不选择它。因此,总共我们有2 * 2 *…(n次)个选择,即2 n
替代解释是:
大小为0的子集数量= n C 0
大小为1的子集数量= n C 1
大小为2的子集数量= n C 2
………………..
子集总数= n C 0 + n C 1 + n C 2 +…。 + n C n = 2 n
有关详细信息,请参考二项式系数之和。

C++
// CPP program to count number of distinct
// subsets in an array of distinct numbers
#include 
using namespace std;
 
// Returns 2 ^ n
int subsetCount(int arr[], int n)
{
    return 1 << n;
}
 
/* Driver program to test above function */
int main()
{
    int A[] = { 1, 2, 3 };
    int n = sizeof(A) / sizeof(A[0]);
 
    cout << subsetCount(A, n);
    return 0;
}


Java
// Java program to count number of distinct
// subsets in an array of distinct numbers
 
class GFG {
     
    // Returns 2 ^ n
    static int subsetCount(int arr[], int n)
    {
        return 1 << n;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int A[] = { 1, 2, 3 };
        int n = A.length;
     
        System.out.println(subsetCount(A, n));
    }
}
 
// This code is contributed by Prerna Saini.


Python3
# Python3 program to count number
# of distinct subsets in an
# array of distinct numbers
import math
 
# Returns 2 ^ n
def subsetCount(arr, n):
 
    return 1 << n
     
# driver code
A = [ 1, 2, 3 ]
n = len(A)
print(subsetCount(A, n))
 
# This code is contributed by Gitanjali.


C#
// C# program to count number of distinct
// subsets in an array of distinct numbers
using System;
 
class GFG {
     
    // Returns 2 ^ n
    static int subsetCount(int []arr, int n)
    {
        return 1 << n;
    }
     
    // Driver program
    public static void Main()
    {
        int []A = { 1, 2, 3 };
        int n = A.Length;
     
        Console.WriteLine(subsetCount(A, n));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:
8