Generate all N digit numbers having absolute difference as K between adjacent digits | Java program for the above approach ; 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
import java . util . * ; class GFG { static void checkUntil ( int num , int K , int N , Vector < Integer > ans ) { if ( N == 1 ) { ans . add ( 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 ) ; } } static void check ( int K , int N , Vector < Integer > ans ) { for ( int i = 1 ; i <= 9 ; i ++ ) { checkUntil ( i , K , N , ans ) ; } } static void print ( Vector < Integer > ans ) { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 4 , K = 8 ; Vector < Integer > ans = new Vector < Integer > ( ) ; ; check ( K , N , ans ) ; print ( ans ) ; } }