Count of N | Java program for the above approach ; Function to count N - digit numbers having absolute difference between adjacent digits in non - increasing order ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If the current digit is 1 , then any digit from [ 1 - 9 ] can be placed ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit i can be placed which satisfies abs ( prev1 - i ) <= abs ( prev1 - prev2 ) ; If absolute difference is less than or equal to diff ; Function to count N - digit numbers with absolute difference between adjacent digits in non increasing order ; Initialize dp table with - 1 ; Function Call ; Driver code
import java . io . * ; class GFG { static int dp [ ] [ ] [ ] = new int [ 100 ] [ 10 ] [ 10 ] ; static int countOfNumbers ( int digit , int prev1 , int prev2 , int n ) { if ( digit == n + 1 ) { return 1 ; } int val = dp [ digit ] [ prev1 ] [ prev2 ] ; if ( val != - 1 ) { return val ; } val = 0 ; if ( digit == 1 ) { for ( int i = ( n == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } else if ( digit == 2 ) { for ( int i = 0 ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } else { int diff = Math . abs ( prev2 - prev1 ) ; for ( int i = 0 ; i <= 9 ; ++ i ) { if ( Math . abs ( prev1 - i ) <= diff ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } } return val ; } static void countNumbersUtil ( int N ) { for ( int i = 0 ; i < 100 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { for ( int k = 0 ; k < 10 ; k ++ ) { dp [ i ] [ j ] [ k ] = - 1 ; } } } System . out . println ( countOfNumbers ( 1 , 0 , 0 , N ) ) ; } public static void main ( String [ ] args ) { int N = 3 ; countNumbersUtil ( N ) ; } }