Count digit groupings of a number with given constraints | C ++ program to count number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated for a given sub problem then return the value ; countGroups for current sub - group is 0 ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; total number of subgroups till current position ; Driver Code ; Initialize dp table
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 40 ; int dp [ MAX ] [ 9 * MAX + 1 ] ; int countGroups ( int position , int previous_sum , int length , char * num ) { if ( position == length ) return 1 ; if ( dp [ position ] [ previous_sum ] != -1 ) return dp [ position ] [ previous_sum ] ; dp [ position ] [ previous_sum ] = 0 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num [ i ] - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } dp [ position ] [ previous_sum ] = res ; return res ; } int main ( ) { char num [ ] = "1119" ; int len = strlen ( num ) ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << countGroups ( 0 , 0 , len , num ) ; return 0 ; }