Count the number of ways to divide N in k groups incrementally | C ++ implementation to count the number of ways to divide N in groups such that each group has K number of elements ; DP Table ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; if N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; put all possible values greater equal to prev ; Function to count the number of ways to divide the number N in groups ; Initialize DP Table as - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 500 ] [ 500 ] [ 500 ] ; int calculate ( int pos , int prev , int left , int k ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos ] [ prev ] [ left ] != -1 ) return dp [ pos ] [ prev ] [ left ] ; int answer = 0 ; for ( int i = prev ; i <= left ; i ++ ) { answer += calculate ( pos + 1 , i , left - i , k ) ; } return dp [ pos ] [ prev ] [ left ] = answer ; } int countWaystoDivide ( int n , int k ) { memset ( dp , -1 , sizeof ( dp ) ) ; return calculate ( 0 , 1 , n , k ) ; } int main ( ) { int N = 8 ; int K = 4 ; cout << countWaystoDivide ( N , K ) ; return 0 ; }