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 program to test above function
function findNDigitNumsUtil ( n , sum , out , index ) { if ( index > n sum < 0 ) return ; if ( index == n ) { if ( sum == 0 ) { out [ index ] = ' \0 ' ; for ( let i = 0 ; i < out . length ; i ++ ) document . write ( out [ i ] ) ; document . write ( " " ) ; } return ; } for ( let i = 0 ; i <= 9 ; i ++ ) { out [ index ] = String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; findNDigitNumsUtil ( n , sum - i , out , index + 1 ) ; } } function findNDigitNums ( n , sum ) { let out = new Array ( n + 1 ) ; for ( let i = 0 ; i < n + 1 ; i ++ ) { out [ i ] = false ; } for ( let i = 1 ; i <= 9 ; i ++ ) { out [ 0 ] = String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; findNDigitNumsUtil ( n , sum - i , out , 1 ) ; } } let n = 2 , sum = 3 ; findNDigitNums ( n , sum ) ;