Generate all N digit numbers having absolute difference as K between adjacent digits | Function that recursively finds the possible numbers and append into ans ; Base Case ; Check the sum of last digit and k less than or equal to 9 or not ; If k == 0 , then subtraction and addition does not make any difference Hence , subtraction is skipped ; Function to call checkUntil function for every integer from 1 to 9 ; check_util function recursively store all numbers starting from i ; Function to print the all numbers which satisfy the conditions ; Given N and K ; To store the result ; Function Call ; Print Resultant Numbers
function checkUntil ( num , K , N , ans ) { if ( N == 1 ) { ans . push ( num ) ; return ; } if ( ( num % 10 + K ) <= 9 ) checkUntil ( 10 * num + ( num % 10 + K ) , K , N - 1 , ans ) ; if ( K > 0 ) { if ( ( num % 10 - K ) >= 0 ) checkUntil ( 10 * num + num % 10 - K , K , N - 1 , ans ) ; } } function check ( K , N , ans ) { for ( let i = 1 ; i <= 9 ; i ++ ) { checkUntil ( i , K , N , ans ) ; } } function print ( ans ) { for ( let i = 0 ; i < ans . length ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } let N = 4 , K = 8 ; let ans = [ ] check ( K , N , ans ) ; print ( ans ) ;