Calculate all states For every state , from numbers 1 to N , the count of numbers which contain exactly j non zero digits is being computed and updated in the dp array .
for ( let i = 0 ; i < n ; ++ i ) { let sm = 0 ; while ( sm < 2 ) { for ( let j = 0 ; j < k + 1 ; ++ j ) { let x = 0 ; while ( x <= ( sm != 0 ? 9 : s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ) { if ( j + ( x > 0 ? 1 : 0 ) < k + 1 ) { dp [ i + 1 ] [ ( sm != 0 || x < ( s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ) ? 1 : 0 ] [ j + ( x > 0 ? 1 : 0 ) ] += dp [ i ] [ sm ] [ j ] ; } ++ x ; } } ++ sm ; } }