The Wayback Machine - https://web.archive.org/web/20241116165947/https://www.geeksforgeeks.org/bell-numbers-number-of-ways-to-partition-a-set/
Open In App

Bell Numbers (Number of ways to Partition a Set)

Last Updated : 09 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
28.95%
6.9K

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


Previous Article
Next Article

Similar Reads

Lynch-Bell Numbers
Lynch-Bell Number is a number N if its digits are all distinct and N is divisible by each of it's digit. 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 24... Given a number N, the task is to check if N is an Lynch-Bell Number or not. If N is an Lynch-Bell Number then print "Yes" else print "No".Examples: Input: N = 384 Output: Yes Explanation: 384/3 = 128, 384
10 min read
Bell numbers in Python
Given a set of n elements, find the number of ways of partitioning it.  Examples:  Input: n = 2Output: Number of ways = 2Explanation: Let the set be {1, 2} { {1}, {2} } { {1, 2} }Input: n = 3Output: Number of ways = 5Explanation: Let the set be {1, 2, 3} { {1}, {2}, {3} } { {1}, {2, 3} } { {2}, {1, 3} } { {3}, {1, 2} } { {1, 2, 3} }. What is a Bell
3 min read
Replace every node in a linked list with its closest bell number
Given a singly linked list, the task is to replace every node with its closest bell number. Bell numbers are a sequence of numbers that represent the number of partitions of a set. In other words, given a set of n elements, the Bell number for n represents the total number of distinct ways that the set can be partitioned into subsets. The first few
15+ min read
Product of nodes with Bell Number weights in a Singly Linked List
Given a singly linked list containing nodes with numeric values and their corresponding weights. The goal is to find the product of the nodes whose weight corresponds Bell Number. Bell numbers are a sequence of numbers that count different combinatorial arrangements, particularly the partitions of a set. These numbers are named after Eric Temple Be
13 min read
Aitken's Array or Bell Triangle
The Bell triangle or Aitken's array or the Pierce Triangle is the number triangle obtained by beginning the first row with the number one, then beginning subsequent rows with the last number of the previous row. The following spaces are filled out by adding the number in the preceding column to the number above it. Follow the image below to better
6 min read
Count number of ways to partition a set into k subsets
Given two numbers n and k where n represents a number of elements in a set, find a number of ways to partition the set into k subsets.Example:  Input: n = 3, k = 2Output: 3Explanation: Let the set be {1, 2, 3}, we can partition it into 2 subsets in following ways {{1,2}, {3}}, {{1}, {2,3}}, {{1,3}, {2}} Input: n = 3, k = 1Output: 1Explanation: Ther
15 min read
Count ways to partition a number into increasing sequences of digits
Given a numeric string S, the task is to find the number of ways to partition a string into substrings consisting of digits in increasing order. Examples: Input: S = "1345"Output: 5Explanation: Possible partitions are as follows: [1345][13, 45], [1, 345][1, 3, 45][1, 3, 4, 5] Input: S = "12"Output: 2 Approach: This problem can be solved by observin
8 min read
Number of ways to partition a string into two balanced subsequences
Given a string 'S' consisting of open and closed brackets, the task is find the number of ways in which each character of 'S' can be assigned to either a string 'X' or string 'Y' (both initially empty) such that the strings formed by X and Y are balanced. It can be assumed that 'S' is itself balanced. Examples: Input: S = "(())"Output: 6Valid assig
15+ min read
Count ways to partition a string such that both parts have equal distinct characters
Content has been removed on Author's request.
1 min read
Count ways to partition a Binary String such that each substring contains exactly two 0s
Given binary string str, the task is to find the count of ways to partition the string such that each partitioned substring contains exactly two 0s. Examples: Input: str = "00100" Output: 2Explanation: Possible ways to partition the string such that each partition contains exactly two 0s are: { {"00", "100"}, {"001", "00"} }. Therefore, the require
6 min read
Count ways to partition Binary Array into subarrays containing K 0s each
Given a binary array arr[] of size N, and an integer K, the task is to calculate the number of ways to partition the array into non-overlapping subarrays, where each subarray has exactly K number 0s. Examples: Input: arr[] = [ 0, 0, 1, 1, 0, 1, 0], K = 2Output: 3Explanation: Different possible partitions are: {{0, 0}, {1, 1, 0, 1, 0}}, {{0, 0, 1},
8 min read
Ways to split string such that each partition starts with distinct character
Given a string s. Let k be the maximum number of partitions possible of the given string with each partition starts with distinct character. The task is to find the number of ways string s can be split into k partition (non-empty) such that each partition start with distinct character. Examples: Input : s = "abb" Output : 2 "abb" can be maximum spl
6 min read
Closest sum partition (into two subsets) of numbers from 1 to n
Given an integer sequence 1, 2, 3, 4, ..., n. The task is to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is the minimum possible. Print the value of |sum(A) - sum(B)|. Examples: Input: 3 Output: 0 A = {1, 2} and B = {3} ans |sum(A) - sum(B)| = |3 - 3| = 0. Input: 6 Output: 0 A = {
4 min read
Segregate even and odd numbers using Lomuto’s Partition Scheme
Given an array arr[] of integers, segregate even and odd numbers in the array such that all the even numbers should be present first, and then the odd numbers. Examples: Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}Output: 2 4 6 8 7 9 1 3 5 Input: arr[] = {1, 3, 2, 4, 7, 6, 9, 10}Output: 2 4 6 10 7 1 9 3 We have discussed two different approaches in S
7 min read
Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
Given three integers a, b and c. You need to select one integer from the range [a, b] and one integer from the range [b, c] and add them. The task to calculate the number of ways to obtain the sum for all the numbers in the range [1, b+c]. Examples: Input: a = 1, b = 2, c = 2 Output: 0, 0, 1, 1 Explanation: The numbers to be obtained are [1, b+c] =
10 min read
Print equal sum sets of array (Partition problem) | Set 1
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Inpu
14 min read
Partition of a set into K subsets with equal sum using BitMask and DP
Given an integer array arr[] of consisting of N integers, the task is check if it is possible to divide the given array into K non-empty subsets of equal sum such that every array element is part of a single subset.Examples: Input: arr[] = {2, 1, 4, 5, 6}, K = 3 Output: Yes Explanation: Possible subsets of given array are {2, 4}, (1, 5} and {6}Inpu
10 min read
Partition a set into two non-empty subsets such that the difference of subset sums is maximum
Given a set of integers S, the task is to divide the given set into two non-empty sets S1 and S2 such that the absolute difference between their sums is maximum, i.e., abs(sum(S1) – sum(S2)) is maximum. Example: Input: S[] = { 1, 2, 1 } Output: 2Explanation:The subsets are {1} and {2, 1}. Their absolute difference is abs(1 - (2+1)) = 2, which is ma
7 min read
Generate all partition of a set
Given a set A = {1, 2, 3, . . ., n }. It is called a partition of the set A if the following conditions follow: The union of all the sets is the set AThe intersection of any two sets is an empty setExamples: Input: n = 3Output: [{1, 2, 3}], [{1, 2}, {3}], [{1, 3}, {2}], [{1}, {2, 3}], [{1}, {2}, {3}]Explanation: For the set {1, 2, 3} these are 5 po
8 min read
Set partition is NP complete
Set partition problem: Set partition problem partitions an array of numbers into two subsets such that the sum of each of these two subsets is the same. Let S be a set of numbers and A is a subset of numbers with sum S1, then there exists another subset containing the remainder of the elements (S - A) with sum S2, and S1 is equaled to S2. Problem S
4 min read
Partition of a set into K subsets with equal sum
Given an integer array of N elements, the task is to divide this array into K non-empty subsets such that the sum of elements in every subset is same. All elements of this array should be part of exactly one partition. Examples: Input : arr = [2, 1, 4, 5, 6], K = 3 Output : Yes we can divide above array into 3 parts with equal sum as [[2, 4], [1, 5
15+ min read
Partition a set into two subsets such that the difference of subset sums is minimum
Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) - sum(Subset2)) should be minimum. Example: Input: arr[] = {1, 6, 1
15+ min read
Partition a Set into Two Subsets of Equal Sum
Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same. Examples: Input: arr[] = [1, 5, 11, 5]Output: True Explanation: The array can be partitioned as [1, 5, 5] and [11] Input: arr[] = [1, 5, 3]Output: False Explanation: The array cannot be partitioned into equal s
15+ min read
Partition first N natural number into two sets such that their sum is not coprime
Given an integer N, the task is to partition the first N natural numbers in two non-empty sets such that the sum of these sets is not coprime to each other. If it is possible then find the possible partition then print -1 else print the sum of elements of both sets.Examples: Input: N = 5 Output: 10 5 {1, 2, 3, 4} and {5} are the valid partitions.In
4 min read
Partition string into two substrings having maximum number of common non-repeating characters
Given a string str, the task is to find the maximum count of common non-repeating characters that can be obtained by partitioning the given string into two non-empty substrings. Examples: Input : str = "aabbca" Output: 2 Explanation: Partition the string into two substrings { { str[0], ... str[2] }, { str[3], ..., str[5] } } The common non-repeatin
15 min read
Partition array into minimum number of equal length subsets consisting of a single distinct value
Given an array arr[] of size N, the task is to print the minimum count of equal length subsets the array can be partitioned into such that each subset contains only a single distinct element Examples: Input: arr[] = { 1, 2, 3, 4, 4, 3, 2, 1 } Output: 4 Explanation: Possible partition of the array is { {1, 1}, {2, 2}, {3, 3}, {4, 4} }. Therefore, th
6 min read
Maximize sum of XOR of each element of Array with partition number
Given an array arr of positive integers of size N, the task is to split the array into 3 partitions, such that the sum of bitwise XOR of each element of the array with its partition number is maximum. Examples: Input: arr[] = { 2, 4, 7, 1, 8, 7, 2 }Output: First partition: 2 4 7 1 8Second partition: 7Third partition: 2Sum: 244 Input: arr[] = {95, 2
9 min read
Find minimum number of non palindromic partition of Binary Array
Given a binary array A[] of length 2*N, the task is to find the minimum number of partitions that follow the below conditions: Each array element belongs to exactly one partitionNone of the partitioned subarrays is a palindrome Note: If there are multiple answers print anyone that satisfies the above conditions and if no such partition exists that
7 min read
Partition a number into two divisible parts
Given a number (as string) and two integers a and b, divide the string in two non-empty parts such that the first part is divisible by a and the second part is divisible by b. If the string can not be divided into two non-empty parts, output "NO", else print "YES" with the two parts. Examples: Input: str = "123", a = 12, b = 3Output: YES 12 3Explan
15+ min read
Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
Given a string str of lowercase English alphabets and an integer m. The task is to count how many positions are there in the string such that if you partition the string into two non-empty sub-strings, there are at least m characters with the same frequency in both sub-strings. The characters need to be present in the string str.Examples: Input: st
15+ min read
three90RightbarBannerImg