Count of N | C ++ program for the above approach ; Function to find the number of N digit numbers such that at least one digit occurs more than once ; Base Case ; If repeated is true , then for remaining positions any digit can be placed ; If the current state has already been computed , then return it ; Stores the count of number for the current recursive calls ; If n = 1 , 0 can be also placed ; If a digit has occurred for the second time , then set repeated to 1 ; Otherwise ; For remaining positions any digit can be placed ; If a digit has occurred for the second time , then set repeated to 1 ; Return the resultant count for the current recursive call ; Function to count all the N - digit numbers having at least one digit 's occurrence more than once ; Initialize dp array with - 1 ; Function to count all possible number satisfying the given criteria ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 50 ] [ 1 << 10 ] [ 2 ] ; int countOfNumbers ( int digit , int mask , bool repeated , int n ) { if ( digit == n + 1 ) { if ( repeated == true ) { return 1 ; } return 0 ; } if ( repeated == true ) { return pow ( 10 , n - digit + 1 ) ; } int & val = dp [ digit ] [ mask ] [ repeated ] ; if ( val != -1 ) { return val ; } val = 0 ; if ( digit == 1 ) { for ( int i = ( n == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { if ( mask & ( 1 << i ) ) { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 1 , n ) ; } else { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 0 , n ) ; } } } else { for ( int i = 0 ; i <= 9 ; ++ i ) { if ( mask & ( 1 << i ) ) { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 1 , n ) ; } else { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 0 , n ) ; } } } return val ; } void countNDigitNumber ( int N ) { memset ( dp , -1 , sizeof dp ) ; cout << countOfNumbers ( 1 , 0 , 0 , N ) ; } int main ( ) { int N = 2 ; countNDigitNumber ( N ) ; return 0 ; }