Count N | C ++ program for the above approach ; Function to count N digit numbers whose digits are less than or equal to the absolute difference of previous two digits ; If all digits are traversed ; If the state has already been computed ; If the current digit is 1 , any digit from [ 1 - 9 ] can be placed . If N == 1 , 0 can also be placed . ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit from 0 to abs ( prev1 - prev2 ) can be placed ; Return the answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 50 ] [ 10 ] [ 10 ] ; long long countOfNumbers ( int digit , int prev1 , int prev2 , int N ) { if ( digit == N + 1 ) return 1 ; if ( dp [ digit ] [ prev1 ] [ prev2 ] != -1 ) return dp [ digit ] [ prev1 ] [ prev2 ] ; dp [ digit ] [ prev1 ] [ prev2 ] = 0 ; if ( digit == 1 ) { for ( int j = ( N == 1 ? 0 : 1 ) ; j <= 9 ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } else if ( digit == 2 ) { for ( int j = 0 ; j <= 9 ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } else { for ( int j = 0 ; j <= abs ( prev1 - prev2 ) ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } return dp [ digit ] [ prev1 ] [ prev2 ] ; } int main ( ) { memset ( dp , -1 , sizeof dp ) ; int N = 3 ; cout << countOfNumbers ( 1 , 0 , 0 , N ) << endl ; return 0 ; }