Total count of sorted numbers upto N digits in range [ L , R ] ( Magnificent necklace combinatorics problem ) | Java program for the above approach ; Function to count total number of ways ; Stores all DP - states ; Stores the result ; Traverse the range [ 0 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Assign dp [ 0 ] [ R - L ] to ans ; Traverse the range [ 1 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Increment ans by dp [ i - 1 ] [ j ] ; Return ans ; Driver Code ; Input ; Function call
import java . util . * ; class GFG { static int Count ( int N , int L , int R ) { int [ ] [ ] dp = new int [ N ] [ R - L + 1 ] ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; } for ( int i = 1 ; i < dp [ 0 ] . length ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 ; } ans = dp [ 0 ] [ R - L ] ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < dp [ 0 ] . length ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ; } ans += dp [ i ] [ R - L ] ; } return ans ; } public static void main ( String args [ ] ) { int N = 3 ; int L = 6 ; int R = 9 ; System . out . println ( Count ( N , L , R ) ) ; } }