N digit numbers having difference between the first and last digits as K | Function to store and check the difference of digits ; Base Case ; Last digit of the number to check the difference from the first digit ; Condition to avoid repeated values ; Update the string pt ; Recursive Call ; Update the string pt ; Recursive Call ; Any number can come in between first and last except the zero ; Recursive Call ; Function to place digit of the number ; When N is 1 and K > 0 , then the single number will be the first and last digit it cannot have difference greater than 0 ; This loop place the digit at the starting ; Recursive Call ; Vector to store results ; Generate all the resultant number ; Print the result ; Driver Code ; Function Call
function findNumbers ( st , result , prev , n , K ) { if ( st . length == n ) { result . push ( parseInt ( st ) ) ; return ; } if ( st . length == n - 1 ) { if ( prev - K >= 0 ) { let pt = " " ; pt += String . fromCharCode ( prev - K + 48 ) ; findNumbers ( st + pt , result , prev - K , n , K ) ; } if ( K != 0 && prev + K < 10 ) { let pt = " " ; pt += String . fromCharCode ( prev + K + 48 ) ; findNumbers ( st + pt , result , prev + K , n , K ) ; } } else { for ( let j = 1 ; j <= 9 ; j ++ ) { let pt = " " ; pt += String . fromCharCode ( j + 48 ) ; findNumbers ( st + pt , result , prev , n , K ) ; } } } function numDifference ( N , K ) { let res = [ ] ; let st = " " ; if ( N == 1 && K == 0 ) { res . push ( 0 ) ; } else if ( N == 1 && K > 0 ) { return res ; } for ( let i = 1 ; i < 10 ; i ++ ) { let temp = " " ; temp += String . fromCharCode ( 48 + i ) ; findNumbers ( st + temp , res , i , N , K ) ; st = " " ; } return res ; } function numDifferenceUtil ( N , K ) { let res = [ ] ; res = numDifference ( N , K ) ; for ( let i = 0 ; i < res . length ; i ++ ) { document . write ( res [ i ] + " " ) ; } } let N = 2 , K = 9 ; numDifferenceUtil ( N , K ) ;