Bell Numbers (Number of ways to Partition a Set)
Last Updated :
23 Jul, 2025
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);
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);
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);
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);
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));
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem