Print all n | 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 Code
def findNDigitNumsUtil ( n , out , index , evenSum , oddSum ) : NEW_LINE INDENT if ( index > n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( abs ( evenSum - oddSum ) == 1 ) : NEW_LINE INDENT out [ index ] = ' ' NEW_LINE out = ' ' . join ( out ) NEW_LINE print ( out , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( index & 1 ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , out , index + 1 , evenSum , oddSum + i ) NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) NEW_LINE DEDENT DEDENT DEDENT def findNDigitNums ( n ) : NEW_LINE INDENT out = [ 0 ] * ( n + 1 ) NEW_LINE index = 0 NEW_LINE evenSum = 0 NEW_LINE oddSum = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT out [ index ] = chr ( i + ord ( '0' ) ) NEW_LINE findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE findNDigitNums ( n ) NEW_LINE DEDENT