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
< ? php function findNDigitNumsUtil ( $ n , $ sum , $ out , $ index ) { if ( $ index > $ n $ sum < 0 ) return ; if ( $ index == $ n ) { if ( $ sum == 0 ) { $ out [ $ index ] = ' ' ; foreach ( $ out as & $ value ) print ( $ value ) ; print ( " ▁ " ) ; } return ; } for ( $ i = 0 ; $ i <= 9 ; $ i ++ ) { $ out [ $ index ] = chr ( $ i + ord ( '0' ) ) ; findNDigitNumsUtil ( $ n , $ sum - $ i , $ out , $ index + 1 ) ; } } function findNDigitNums ( $ n , $ sum ) { $ out = array_fill ( 0 , $ n + 1 , false ) ; for ( $ i = 1 ; $ i <= 9 ; $ i ++ ) { $ out [ 0 ] = chr ( $ i + ord ( '0' ) ) ; findNDigitNumsUtil ( $ n , $ sum - $ i , $ out , 1 ) ; } } $ n = 2 ; $ sum = 3 ; findNDigitNums ( $ n , $ sum ) ; ? >