Open In App

Bell Numbers (Number of ways to Partition a Set)

Last Updated : 09 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a set of n elements, find the number of ways of partitioning it. 

Examples: 

Input: n = 2
Output: 2
Explanation: Let the set be {1, 2}. The partitions are {{1},{2}} and {{1, 2}}.

Input: n = 3
Output: 5
Explanation: Let the set be {1, 2, 3}. The partitions are {{1},{2},{3}}, {{1},{2, 3}}, {{2},{1, 3}}, {{3},{1, 2}}, {{1, 2, 3}}.

What is a Bell Number? 
Let S(n, k) be total number of partitions of n elements into k sets. The value of the n'th Bell Number is the sum of S(n, k) for k = 1 to n
Bell(n)=∑​S (n,k) for k ranges from [1,n]
Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1)

How does above recursive formula work? 
When we add a (n+1)'th element to k partitions, there are two possibilities. 
1) It is added as a single element set to existing partitions, i.e, S(n, k-1) 
2) It is added to all sets of every partition, i.e., k*S(n, k).
First few Bell numbers are 1, 1, 2, 5, 15, 52, 203, .... 

Using recursion - O(2 ^ n)  Time and O(n) Space

We can recursively calculate the number of ways to partition a set of n elements by considering each element and either placing it in an existing subset or creating a new subset. For each element, we calculate the number of ways to partition the remaining n-1 elements into k subsets and then sum these values for all possible k. This gives us the following recurrence relation for Stirling numbers of the second kind:

  • S(n,k) = k * S( n - 1, k) + S(n - 1, k - 1)

Finally, to find the Bell number, we sum S(n, k) for all values of k from 1 to n. This gives us the total number of ways to partition the set.

C++
// C++ code of finding the bellNumber 
// using recursion 

#include <iostream>
#include <vector>

using namespace std;

// Function to compute Stirling numbers of
// the second kind S(n, k) with memoization
int stirling(int n, int k) {
  
    // Base cases
    if (n == 0 && k == 0) return 1;
    if (k == 0 || n == 0) return 0;
    if (n == k) return 1;
    if (k == 1) return 1;


    // Recursive formula
    return k * stirling(n - 1, k) + stirling(n - 1, k - 1);
}

// Function to calculate the total number of 
// ways to partition a set of `n` elements
int bellNumber(int n) {
  
    int result = 0;

    // Sum up Stirling numbers S(n, k) for all
  	// k from 1 to n
    for (int k = 1; k <= n; ++k) {
        result += stirling(n, k);
    }
    return result;
}

int main() {
  
    int n = 5;
    int result = bellNumber(n);
    cout << result << endl;

    return 0;
}
Java
// Java program to find the Bell Number
// using recursion

class GfG {
  
    // Function to compute Stirling numbers of
    // the second kind S(n, k) with memoization
    static int stirling(int n, int k) {
      
        // Base cases
        if (n == 0 && k == 0) return 1;
        if (k == 0 || n == 0) return 0;
        if (n == k) return 1;
        if (k == 1) return 1;

        // Recursive formula
        return k * stirling(n - 1, k) + stirling(n - 1, k - 1);
    }

    // Function to calculate the total number of 
    // ways to partition a set of `n` elements
    static int bellNumber(int n) {
      
        int result = 0;

        // Sum up Stirling numbers S(n, k) for 
      	// all k from 1 to n
        for (int k = 1; k <= n; ++k) {
            result += stirling(n, k);
        }
        return result;
    }

    public static void main(String[] args) {
      
        int n = 5;
        int result = bellNumber(n);
        System.out.println(result);
    }
}
Python
# Python program to find the Bell Number using recursion

# Function to compute Stirling numbers of
# the second kind S(n, k) with memoization
def stirling(n, k):
  
    # Base cases
    if n == 0 and k == 0: return 1
    if k == 0 or n == 0: return 0
    if n == k: return 1
    if k == 1: return 1

    # Recursive formula
    return k * stirling(n - 1, k) + stirling(n - 1, k - 1)

# Function to calculate the total number of 
# ways to partition a set of `n` elements
def bellNumber(n):

    result = 0

    # Sum up Stirling numbers S(n, k) for
    # all k from 1 to n
    for k in range(1, n + 1):
        result += stirling(n, k)
    return result

n = 5
result = bellNumber(n)
print(result)
C#
// C# program to find the Bell Number
// using recursion

using System;

class GfG {
  
    // Function to compute Stirling numbers of
    // the second kind S(n, k) with memoization
    static int Stirling(int n, int k) {
      
        // Base cases
        if (n == 0 && k == 0) return 1;
        if (k == 0 || n == 0) return 0;
        if (n == k) return 1;
        if (k == 1) return 1;

        // Recursive formula
        return k * Stirling(n - 1, k) + Stirling(n - 1, k - 1);
    }

    // Function to calculate the total number of 
    // ways to partition a set of `n` elements
    static int BellNumber(int n) {
      
        int result = 0;

        // Sum up Stirling numbers S(n, k) for all
      	// k from 1 to n
        for (int k = 1; k <= n; ++k) {
            result += Stirling(n, k);
        }
        return result;
    }

    public static void Main(string[] args) {
        int n = 5;

        int result = BellNumber(n);
        Console.WriteLine(result);
    }
}
JavaScript
// JavaScript program to find the Bell Number using recursion

// Function to compute Stirling numbers of
// the second kind S(n, k) with memoization
function stirling(n, k) {

    // Base cases
    if (n === 0 && k === 0) return 1;
    if (k === 0 || n === 0) return 0;
    if (n === k) return 1;
    if (k === 1) return 1;

    // Recursive formula
    return k * stirling(n - 1, k) + stirling(n - 1, k - 1);
}

// Function to calculate the total number of 
// ways to partition a set of `n` elements
function bellNumber(n) {

    let result = 0;

    // Sum up Stirling numbers S(n, k) for all
    // k from 1 to n
    for (let k = 1; k <= n; ++k) {
        result += stirling(n, k);
    }
    return result;
}

let n = 5;
let result = bellNumber(n);
console.log(result);

Output
52

Using Top-Down DP (Memoization) - O(n^2) Time and O(n^2) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

1. Optimal Substructure: The number of ways to partition a set of n elements into k subsets depends on two smaller subproblems:

  • The number of ways to partition the first n-1 elements into k subsets, and
  • The number of ways to partition the first n-1 elements into k-1 subsets and then add the new element as its own subset. By combining these optimal solutions, we can efficiently calculate the total number of ways to partition the set.

2. Overlapping Subproblems: In the recursive approach, certain subproblems are recalculated multiple times. For example, when computing S(n, k), the subproblems S(n-1, k) and S(n-1, k-1) are recomputed multiple times. This redundancy leads to overlapping subproblems, which can be avoided using memoization or tabulation.

Follow the steps below to solve the problem:

  • Use recursion with memoization to calculate Stirling numbers of the second kind, S(n,k), which represent the number of ways to partition n items into k non-empty subsets.
  • Define base cases for S(0, 0), S(n, 0), S(n, n), and S(n, 1) to handle specific situations in the recursive formula.
  • Use the formula S(n, k) = k × S(n-1, k) + S(n-1, k-1) to compute the Stirling numbers with previously stored results.
  • For a given n, sum S(n, k) for all from 1 to n to calculate the Bell number, which represents the total ways to partition n elements.
  • Output the computed Bell number for the given n.
C++
// C++ code of finding the bellNumber
// using Memoization 

#include <iostream>
#include <vector>

using namespace std;

// Function to compute Stirling numbers of
// the second kind S(n, k) with memoization

int stirling(int n, int k, vector<vector<int>>& memo) {
  
    // Base cases
    if (n == 0 && k == 0) return 1;
    if (k == 0 || n == 0) return 0;
    if (n == k) return 1;
    if (k == 1) return 1;

    // Check if result is already computed
    if (memo[n][k] != -1) return memo[n][k];

    // Recursive formula
    memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo);
    return memo[n][k];
}

// Function to calculate the total number of 
// ways to partition a set of `n` elements
int bellNumber(int n) {
  
    // Initialize memoization table with -1
    vector<vector<int>> memo(n + 1, vector<int>(n + 1, -1));
    int result = 0;

    // Sum up Stirling numbers S(n, k) for all
  	// k from 1 to n
    for (int k = 1; k <= n; ++k) {
        result += stirling(n, k, memo);
    }
    return result;
}

int main() {
  
    int n = 5;
    int result = bellNumber(n);
    cout << result << endl;

    return 0;
}
Java
// Java code of finding the bellNumber
// using Memoization 

import java.util.Arrays;

class GfG {

    // Function to compute Stirling numbers of
    // the second kind S(n, k) with memoization
    static int stirling(int n, int k, int[][] memo) {
      
        // Base cases
        if (n == 0 && k == 0) return 1;
        if (k == 0 || n == 0) return 0;
        if (n == k) return 1;
        if (k == 1) return 1;

        // Check if result is already computed
        if (memo[n][k] != -1) return memo[n][k];

        // Recursive formula
        memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo);
        return memo[n][k];
    }

    // Function to calculate the total number of 
    // ways to partition a set of n elements
    static int bellNumber(int n) {
      
        // Initialize memoization table with -1
        int[][] memo = new int[n + 1][n + 1];
        for (int[] row : memo) Arrays.fill(row, -1);
        int result = 0;

        // Sum up Stirling numbers S(n, k) for all k from 1 to n
        for (int k = 1; k <= n; ++k) {
            result += stirling(n, k, memo);
        }
        return result;
    }

    public static void main(String[] args) {
        int n = 5;
        int result = bellNumber(n);
        System.out.println(result);
    }
}
Python
# Python code of finding the bellNumber
# Using Memoization

# Function to compute Stirling numbers of
# the second kind S(n, k) with memoization

def stirling(n, k, memo):

    # Base cases
    if n == 0 and k == 0:
        return 1
    if k == 0 or n == 0:
        return 0
    if n == k:
        return 1
    if k == 1:
        return 1

    # Check if result is already 
    # computed
    if memo[n][k] != -1:
        return memo[n][k]

    # Recursive formula
    memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo)
    return memo[n][k]

# Function to calculate the total number of
# ways to partition a set of n elements

def bellNumber(n):
  
    # Initialize memoization table with -1
    memo = [[-1 for _ in range(n + 1)] for _ in range(n + 1)]
    result = 0

    # Sum up Stirling numbers S(n, k) for all k from 1 to n
    for k in range(1, n + 1):
        result += stirling(n, k, memo)
    return result

if __name__ == "__main__":
  
    n = 5
    result = bellNumber(n)
    print(result)
C#
//C# code of finding the bellNumber
// using Memoization 

using System;

class GfG {

    // Function to compute Stirling numbers of
    // the second kind S(n, k) with memoization
    static int Stirling(int n, int k, int[, ] memo) {
      
        // Base cases
        if (n == 0 && k == 0)
            return 1;
        if (k == 0 || n == 0)
            return 0;
        if (n == k)
            return 1;
        if (k == 1)
            return 1;

        // Check if result is already
      	// computed
        if (memo[n, k] != -1)
            return memo[n, k];

        // Recursive formula
        memo[n, k] = k * Stirling(n - 1, k, memo)
                   + Stirling(n - 1, k - 1, memo);
        return memo[n, k];
    }

    // Function to calculate the total number of
    // ways to partition a set of n elements
    static int BellNumber(int n) {
      
        // Initialize memoization table with -1
        int[, ] memo = new int[n + 1, n + 1];
        for (int i = 0; i <= n; i++)
            for (int j = 0; j <= n; j++)
                memo[i, j] = -1;
        int result = 0;

        // Sum up Stirling numbers S(n, k) for all k from 1
        // to n
        for (int k = 1; k <= n; ++k) {
            result += Stirling(n, k, memo);
        }
        return result;
    }

    static void Main(string[] args) {
      
        int n = 5;
        int result = BellNumber(n);
        Console.WriteLine(result);
    }
}
JavaScript
// JavaScript code of finding the bellNumber
// using Memoization 


// Function to compute Stirling numbers of
// the second kind S(n, k) with memoization
function stirling(n, k, memo) {

    // Base cases
    if (n === 0 && k === 0) return 1;
    if (k === 0 || n === 0) return 0;
    if (n === k) return 1;
    if (k === 1) return 1;

    // Check if result is already computed
    if (memo[n][k] !== -1) return memo[n][k];

    // Recursive formula
    memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo);
    return memo[n][k];
}

// Function to calculate the total number of 
// ways to partition a set of n elements
function bellNumber(n) {

    // Initialize memoization table with -1
    let memo = Array.from({ length: n + 1 }, () => Array(n + 1).fill(-1));
    let result = 0;

    // Sum up Stirling numbers S(n, k) for all k from 1 to n
    for (let k = 1; k <= n; ++k) {
        result += stirling(n, k, memo);
    }
    return result;
}

let n = 5;
let result = bellNumber(n);
console.log(result);

Output
52

Using Bottom-Up DP (Tabulation - 1) - O(n^2) Time and O(n^2) Space

A Simple Method to compute n'th Bell Number is to one by one compute S(n, k) for k = 1 to n and return sum of all computed values. Refer Count number of ways to partition a set into k subsets for computation of S(n, k).

C++
// C++ code to calculate the Bell number for a given
// integer `n`
#include <iostream>
#include <vector>
using namespace std;

// Function to calculate the Bell number for a given integer `n`
int bellNumber(int n) {

    // Create a 2D vector for Stirling numbers of
  	// the second kind
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));

    // Fill the table using dynamic programming
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {

            // These are some base cases
            if (j > i)
                dp[i][j] = 0;
            else if (i == j)
                dp[i][j] = 1;
            else if (i == 0 || j == 0)
                dp[i][j] = 0;
            else {

                // Recurrence relation: Stirling number calculation
                dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1];
            }
        }
    }

    // Sum up Stirling numbers for all j
    // from 0 to n to get the Bell number
    int ans = 0;
    for (int i = 0; i <= n; i++)
    {
        ans += dp[n][i];
    }

    // Return the Bell number
    return ans;
}

int main() {

    int n = 5;
    int result = bellNumber(n);
    cout << result << endl;

    return 0;
}
Java
// Java code to calculate the Bell number for a given
// integer `n`

class GfG {

    // Function to calculate the Bell number for a given
    // integer `n`
    static int bellNumber(int n) {

        // Create a 2D vector for Stirling numbers of the
        // second kind
        int[][] dp = new int[n + 1][n + 1];

        // Fill the table using dynamic programming
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {

                // These are some base cases
                if (j > i)
                    dp[i][j] = 0;
                else if (i == j)
                    dp[i][j] = 1;
                else if (i == 0 || j == 0)
                    dp[i][j] = 0;
                else {

                    // Recurrence relation: Stirling number
                    // calculation
                    dp[i][j]
                        = j * dp[i - 1][j] + dp[i - 1][j - 1];
                }
            }
        }

        // Sum up Stirling numbers for all j
        // from 0 to n to get the Bell number
        int ans = 0;
        for (int i = 0; i <= n; i++) {
            ans += dp[n][i];
        }

        // Return the Bell number
        return ans;
    }

    public static void main(String[] args) {

        int n = 5;
        int result = bellNumber(n);
        System.out.println(result);
    }
}
Python
# Python code to calculate the Bell number for a given integer `n`

# Function to calculate the Bell number for a
# given integer `n`
def bellNumber(n):

    # Create a 2D list for Stirling numbers of
    # the second kind
    dp = [[0] * (n + 1) for _ in range(n + 1)]

    # Fill the table using dynamic programming
    for i in range(n + 1):
        for j in range(n + 1):

            # These are some base cases
            if j > i:
                dp[i][j] = 0
            elif i == j:
                dp[i][j] = 1
            elif i == 0 or j == 0:
                dp[i][j] = 0
            else:

                # Recurrence relation: Stirling number calculation
                dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]

    # Sum up Stirling numbers for all j
    # from 0 to n to get the Bell number
    ans = 0
    for i in range(n + 1):
        ans += dp[n][i]

    # Return the Bell number
    return ans


if __name__ == "__main__":

    n = 5
    result = bellNumber(n)
    print(result)
C#
// C# code to calculate the Bell number for a given integer
// `n`

using System;

class GfG {

    // Function to calculate the Bell number for a given
    // integer `n`
    static int BellNumber(int n) {

        // Create a 2D array for Stirling numbers of the
        // second kind
        int[, ] dp = new int[n + 1, n + 1];

        // Fill the table using dynamic programming
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {

                // These are some base cases
                if (j > i)
                    dp[i, j] = 0;
                else if (i == j)
                    dp[i, j] = 1;
                else if (i == 0 || j == 0)
                    dp[i, j] = 0;
                else {

                    // Recurrence relation: Stirling number
                    // calculation
                    dp[i, j]
                        = j * dp[i - 1, j] + dp[i - 1, j - 1];
                }
            }
        }

        // Sum up Stirling numbers for all j
        // from 0 to n to get the Bell number
        int ans = 0;
        for (int i = 0; i <= n; i++) {
            ans += dp[n, i];
        }

        // Return the Bell number
        return ans;
    }

    static void Main(string[] args) {

        int n = 5;
        int result = BellNumber(n);
        Console.WriteLine(result);
    }
}
Javascript
// JavaScript code to calculate the Bell number for a given
// integer `n`

// Function to calculate the Bell number for a given integer
// `n`
function bellNumber(n) {

    // Create a 2D array for Stirling numbers of the second
    // kind
    let dp = Array.from({length : n + 1},
                       () => Array(n + 1).fill(0));

    // Fill the table using dynamic programming
    for (let i = 0; i <= n; i++) {
        for (let j = 0; j <= n; j++) {

            // These are some base cases
            if (j > i)
                dp[i][j] = 0;
            else if (i === j)
                dp[i][j] = 1;
            else if (i === 0 || j === 0)
                dp[i][j] = 0;
            else {

                // Recurrence relation: Stirling number
                // calculation
                dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1];
            }
        }
    }

    // Sum up Stirling numbers for all j
    // from 0 to n to get the Bell number
    let ans = 0;
    for (let i = 0; i <= n; i++) {
        ans += dp[n][i];
    }

    // Return the Bell number
    return ans;
}

let n = 5;
let result = bellNumber(n);
console.log(result);

Output
52

Using Bottom-Up DP (Tabulation - 2) - O(n^2) Time and O(n^2) Space

A Better Method is to use Bell Triangle. Below is a sample Bell Triangle for first few Bell Numbers. 

1
1 2
2 3 5
5 7 10 15
15 20 27 37 52

Follow the steps below to solve the problem:

  • Create a 2D array to store Bell numbers, starting with bell[0][0] = 1 as the base case.
  • Use dynamic programming to fill the table based on the recurrence relation. For each i, set bell[i][0] = bell[i-1][i-1] and compute bell[i][j] using the formula bell[i][j] = bell[i-1][j-1] + bell[i][j-1] for all valid j.
  • The formula computes the Bell numbers by using the Stirling numbers of the second kind, which count ways to partition a set of i elements into j non-empty subsets.
  • The Bell number for n is stored in bell[n][0].
C++14
// A C++ program to find n'th Bell number
#include <iostream>
using namespace std;

int bellNumber(int n) {
  
    int dp[n + 1][n + 1];
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++) {
      
        // Explicitly fill for j = 0
        dp[i][0] = dp[i - 1][i - 1];

        // Fill for remaining values of j
        for (int j = 1; j <= i; j++)
            dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1];
    }
    return dp[n][0];
}


int main() {
  
    int n = 5;
    int result = bellNumber(n);
    cout << result << endl;
    return 0;
}
Java
// Java program to find n'th Bell number

class GfG {

    // Function to calculate the Bell number for a given
    // integer `n`
    static int bellNumber(int n) {
        int[][] dp = new int[n + 1][n + 1];
        dp[0][0] = 1;

        for (int i = 1; i <= n; i++) {
          
            // Explicitly fill for j = 0
            dp[i][0] = dp[i - 1][i - 1];

            // Fill for remaining values of j
            for (int j = 1; j <= i; j++)
                dp[i][j]
                    = dp[i - 1][j - 1] + dp[i][j - 1];
        }
        return dp[n][0];
    }

    public static void main(String[] args) {
      
        int n = 5;
        int result = bellNumber(n);
        System.out.println(result);
    }
}
Python
# Python program to find n'th Bell number

# Function to calculate the Bell number for a given integer `n`
def bellNumber(n):
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    dp[0][0] = 1

    for i in range(1, n + 1):
      
        # Explicitly fill for j = 0
        dp[i][0] = dp[i - 1][i - 1]

        # Fill for remaining values of j
        for j in range(1, i + 1):
            dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]

    return dp[n][0]


if __name__ == "__main__":
  
    n = 5
    result = bellNumber(n)
    print(result)
C#
// C# program to find n'th Bell number

using System;

class GfG {

    // Function to calculate the Bell number for a given
    // integer `n`
    static int BellNumber(int n) {
      
        int[, ] dp = new int[n + 1, n + 1];
        dp[0, 0] = 1;

        for (int i = 1; i <= n; i++) {
          
            // Explicitly fill for j = 0
            dp[i, 0] = dp[i - 1, i - 1];

            // Fill for remaining values of j
            for (int j = 1; j <= i; j++)
                dp[i, j]
                    = dp[i - 1, j - 1] + dp[i, j - 1];
        }
      
        return dp[n, 0];
    }

    static void Main(string[] args) {
      
        int n = 5;
        int result = BellNumber(n);
        Console.WriteLine(result);
    }
}
Javascript
// JavaScript program to find n'th Bell number

// Function to calculate the Bell number for a given integer
// `n`
function bellNumber(n) {

    let dp = Array.from({length : n + 1},
                          () => Array(n + 1).fill(0));
    dp[0][0] = 1;

    for (let i = 1; i <= n; i++) {
    
        // Explicitly fill for j = 0
        dp[i][0] = dp[i - 1][i - 1];

        // Fill for remaining values of j
        for (let j = 1; j <= i; j++) {
            dp[i][j]
                = dp[i - 1][j - 1] + dp[i][j - 1];
        }
    }

    return dp[n][0];
}

let n = 5;
let result = bellNumber(n);
console.log(result);

Output
52

Using Space Optimized DP - O(n^2) Time and O(n) Space

We can use a 1-D array to represent the previous row of the Bell triangle. We initialize dp[0] to 1, since there is only one way to partition an empty set.

To compute the Bell numbers for n > 0, we first set dp[0] = dp[i-1], since the first element in each row is the same as the last element in the previous row. Then, we use the recurrence relation dp[j] = prev + dp[j-1] to compute the Bell number for each partition, where prev is the value of dp[j] in the previous iteration of the inner loop. We update prev to the temporary variable temp before updating dp[j]. Finally, we return dp[0], which is the Bell number for the partition of a set with n elements into non-empty subsets.

C++
// C++ program to find n'th Bell number using
// tabulation
#include <iostream>
#include <vector>
using namespace std;

// Function to calculate the Bell number for 'n'
int bellNumber(int n) {
  
    // Initialize the previous row of the Bell triangle with
    // dp[0] = 1
    vector<int> dp(n + 1, 0);
    dp[0] = 1;

    for (int i = 1; i <= n; i++) {
      
        // The first element in each row is the same as the
        // last element in the previous row
        int prev = dp[0];
        dp[0] = dp[i - 1];
        for (int j = 1; j <= i; j++) {
          
            // The Bell number for n is the sum of the Bell
            // numbers for all previous partitions
            int temp = dp[j];
            dp[j] = prev + dp[j - 1];
            prev = temp;
        }
    }

    return dp[0];
}

int main() {
  
    int n = 5;
    cout << bellNumber(n) << std::endl;
    return 0;
}
Java
// Java program to find n'th Bell number using
// tabulation
import java.util.Arrays;

class GfG {

    // Function to calculate the Bell number for 'n'
    static int bellNumbers(int n) {
      
        // Initialize the previous row of the Bell triangle
        // with dp[0] = 1
        int[] dp = new int[n + 1];
        Arrays.fill(dp, 0);
        dp[0] = 1;

        for (int i = 1; i <= n; i++) {
          
            // The first element in each row is the same as
            // the last element in the previous row
            int prev = dp[0];
            dp[0] = dp[i - 1];

            for (int j = 1; j <= i; j++) {
              
                // The Bell number for n is the sum of the
                // Bell numbers for all previous partitions
                int temp = dp[j];
                dp[j] = prev + dp[j - 1];
                prev = temp;
            }
        }

        return dp[0];
    }

    public static void main(String[] args) {
      
        int n = 5;
        System.out.println(bellNumbers(n));
    }
}
Python
# Python program to find n'th Bell number using
# tabulation

def bell_numbers(n):
  
    # Initialize the previous row of the
    # Bell triangle with dp[0] = 1
    dp = [1] + [0] * n

    for i in range(1, n + 1):
      
        # The first element in each row is the same 
        # as the last element in the previous row
        prev = dp[0]
        dp[0] = dp[i - 1]
        for j in range(1, i + 1):
          
            # The Bell number for n is the sum of the
            # Bell numbers for all previous partitions
            temp = dp[j]
            dp[j] = prev + dp[j - 1]
            prev = temp

    return dp[0]

n = 5
print(bell_numbers(n))
C#
// C# program to find n'th Bell number using
// tabulation
using System;

class GfG {
  
    // Function to calculate the Bell number for 'n'
    static int BellNumbers(int n) {
      
        // Initialize the previous row of the Bell triangle
        // with dp[0] = 1
        int[] dp = new int[n + 1];
        dp[0] = 1;

        for (int i = 1; i <= n; i++) {
          
            // The first element in each row is the same as
            // the last element in the previous row
            int prev = dp[0];
            dp[0] = dp[i - 1];

            for (int j = 1; j <= i; j++) {
              
                // The Bell number for n is the sum of the
                // Bell numbers for all previous partitions
                int temp = dp[j];
                dp[j] = prev + dp[j - 1];
                prev = temp;
            }
        }

        return dp[0];
    }

    static void Main() {
      
        int n = 5;
        Console.WriteLine(BellNumbers(n));
    }
}
Javascript
// JavaScript program to find n'th Bell number using
// tabulation
function bellNumbers(n) {

    // Create an array to store intermediate values,
    // initialized with zeros
    let dp = new Array(n + 1).fill(0);
    
    // The first element represents the Bell number for 0,
    // which is 1
    dp[0] = 1;

    // Iterate through each row of the Bell triangle up to
    // 'n'
    for (let i = 1; i <= n; i++) {
    
        // Store the value of the first element in the
        // current row
        let prev = dp[0];
        
        // Update the first element of the row using the
        // last element of the previous row

        dp[0] = dp[i - 1];

        // Iterate through each element in the current row
        for (let j = 1; j <= i; j++) {
        
            // Store the current value of dp[j] in a
            // temporary variable
            let temp = dp[j];
            
            // Update dp[j] by adding the previous value
            // (prev) and the value at dp[j-1]
            dp[j] = prev + dp[j - 1];
            
            // Update the 'prev' variable for the next
            // iteration of the inner loop
            prev = temp;
        }
    }

    // Return the Bell number for 'n'
    return dp[0];
}

let n = 5;
console.log(bellNumbers(n));

Output
52

Next Article

Similar Reads