Count of n digit numbers whose sum of digits equals to given sum | A lookup table used for memoization ; Memoization based implementation of recursive function ; Base case ; If this subproblem is already evaluated , return the evaluated value ; Initialize answer ; Traverse through every digit and recursively count numbers beginning with it ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining n . ; Initialize final answer ; Traverse through every digit from 1 to 9 and count numbers beginning with it ; Driver Code
lookup = [ [ - 1 for i in range ( 501 ) ] for i in range ( 101 ) ] NEW_LINE def countRec ( n , Sum ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return Sum == 0 NEW_LINE DEDENT if ( lookup [ n ] [ Sum ] != - 1 ) : NEW_LINE INDENT return lookup [ n ] [ Sum ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( Sum - i >= 0 ) : NEW_LINE INDENT ans += countRec ( n - 1 , Sum - i ) NEW_LINE DEDENT DEDENT lookup [ n ] [ Sum ] = ans NEW_LINE return lookup [ n ] [ Sum ] NEW_LINE DEDENT def finalCount ( n , Sum ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( Sum - i >= 0 ) : NEW_LINE INDENT ans += countRec ( n - 1 , Sum - i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n , Sum = 3 , 5 NEW_LINE print ( finalCount ( n , Sum ) ) NEW_LINE