Count number of ways to partition a set into k subsets | A Dynamic Programming based Java program to count number of partitions of a set with n elements into k subsets ; Returns count of different partitions of n elements in k subsets ; Table to store results of subproblems ; Base cases ; Fill rest of the entries in dp [ ] [ ] in bottom up manner ; Driver program
class GFG { static int countP ( int n , int k ) { int [ ] [ ] dp = new int [ n + 1 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int i = 0 ; i <= k ; i ++ ) dp [ 0 ] [ k ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= k ; j ++ ) if ( j == 1 i == j ) dp [ i ] [ j ] = 1 ; else dp [ i ] [ j ] = j * dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - 1 ] ; return dp [ n ] [ k ] ; } public static void main ( String [ ] args ) { System . out . println ( countP ( 5 , 2 ) ) ; } }