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 ; Driver Code ; Given N and K ; To store the result ; Function call ; Print resultant numbers
def checkUntil ( num , K , N , ans ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT ans . append ( num ) NEW_LINE return NEW_LINE DEDENT if ( ( num % 10 + K ) <= 9 ) : NEW_LINE INDENT checkUntil ( 10 * num + ( num % 10 + K ) , K , N - 1 , ans ) NEW_LINE DEDENT if ( K ) : NEW_LINE INDENT if ( ( num % 10 - K ) >= 0 ) : NEW_LINE INDENT checkUntil ( 10 * num + num % 10 - K , K , N - 1 , ans ) NEW_LINE DEDENT DEDENT DEDENT def check ( K , N , ans ) : NEW_LINE INDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT checkUntil ( i , K , N , ans ) NEW_LINE DEDENT DEDENT def print_list ( ans ) : NEW_LINE INDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " , ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE K = 8 ; NEW_LINE ans = [ ] NEW_LINE check ( K , N , ans ) NEW_LINE print_list ( ans ) NEW_LINE DEDENT