Print all n | Java program to print all n - digit numbers with absolute difference between sum of even and odd digits is 1 ; n -- > value of input out -- > output array index -- > index of next digit to be filled in output array evenSum , oddSum -- > sum of even and odd digits so far ; Base case ; If number becomes n - digit ; if absolute difference between sum of even and odd digits is 1 , print the number ; If current index is odd , then add it to odd sum and recurse ; else else add to even sum and recurse ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit and calls findNDigitNumsUtil ( ) for remaining indexes ; output array to store n - digit numbers ; Initialize number index considered so far ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function findNDigitNumsUtil for remaining indexes . Note that the first digit is considered to be present in even position ; Driver program
import java . io . * ; import java . util . * ; class GFG { static void findNDigitNumsUtil ( int n , char out [ ] , int index , int evenSum , int oddSum ) { if ( index > n ) return ; if ( index == n ) { if ( Math . abs ( evenSum - oddSum ) == 1 ) { out [ index ] = ' ▁ ' ; System . out . print ( out ) ; } return ; } if ( index % 2 != 0 ) { for ( int i = 0 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , out , index + 1 , evenSum , oddSum + i ) ; } } { for ( int i = 0 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) ; } } } static void findNDigitNums ( int n ) { char [ ] out = new char [ n + 1 ] ; int index = 0 ; int evenSum = 0 , oddSum = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) ; } } public static void main ( String [ ] args ) { int n = 3 ; findNDigitNums ( n ) ; } }