N digit numbers having difference between the first and last digits as K | Java program for the above approach ; 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
import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static void findNumbers ( String st , ArrayList result , int prev , int n , int K ) { if ( st . length ( ) == n ) { result . add ( Integer . parseInt ( st ) ) ; return ; } if ( st . length ( ) == n - 1 ) { if ( prev - K >= 0 ) { String pt = " " ; pt += ( char ) ( prev - K + 48 ) ; findNumbers ( st + pt , result , prev - K , n , K ) ; } if ( K != 0 && prev + K < 10 ) { String pt = " " ; pt += ( char ) ( prev + K + 48 ) ; findNumbers ( st + pt , result , prev + K , n , K ) ; } } else { for ( int j = 1 ; j <= 9 ; j ++ ) { String pt = " " ; pt += ( char ) ( j + 48 ) ; findNumbers ( st + pt , result , prev , n , K ) ; } } } static ArrayList numDifference ( int N , int K ) { ArrayList res = new ArrayList ( ) ; String st = " " ; if ( N == 1 && K == 0 ) { res . add ( 0 ) ; } else if ( N == 1 && K > 0 ) { return res ; } for ( int i = 1 ; i < 10 ; i ++ ) { String temp = " " ; temp += ( char ) ( 48 + i ) ; findNumbers ( st + temp , res , i , N , K ) ; st = " " ; } return res ; } static void numDifferenceUtil ( int N , int K ) { ArrayList res = new ArrayList ( ) ; res = numDifference ( N , K ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { System . out . print ( res . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 2 , K = 9 ; numDifferenceUtil ( N , K ) ; } }