Print all n | n , sum -- > value of inputs out -- > output array index -- > index of next digit to be filled in output array ; Base case ; If number becomes N - digit ; if sum of its digits is equal to given sum , print it ; Traverse through every digit . Note that here we ' re ▁ considering ▁ leading ▁ ▁ 0' s as digits ; append current digit to number ; recurse for next digit with reduced sum ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit ; output array to store N - digit numbers ; fill 1 st position by every digit from 1 to 9 and calls findNDigitNumsUtil ( ) for remaining positions ; Driver Code
def findNDigitNumsUtil ( n , sum , out , index ) : NEW_LINE INDENT if ( index > n or sum < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT f = " " NEW_LINE if ( index == n ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT out [ index ] = " \0" NEW_LINE for i in out : NEW_LINE INDENT f = f + i NEW_LINE DEDENT print ( f , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , sum - i , out , index + 1 ) NEW_LINE DEDENT DEDENT def findNDigitNums ( n , sum ) : NEW_LINE INDENT out = [ False ] * ( n + 1 ) NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT out [ 0 ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , sum - i , out , 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE sum = 3 NEW_LINE findNDigitNums ( n , sum ) NEW_LINE DEDENT