Total number of non-decreasing numbers with n digits
Total number of non-decreasing numbers with n digits
In the total number of non-decreasing numbers problem, we have to find all numbers of length 1 to n such that the digits in numbers are in increasing order. The problem can be solved using dynamic programming. In the article, we will provide a C++ solution with an explanation.
Total number of non-decreasing numbers Problem Description
Input:
- First-line contains integer n.
Output:
- Single Integer, the required count.
Total number of non-decreasing numbers Problem Solution
Steps required are –
Function Definition –Let F(id,prev) = no. of numbers such that digit prev is placed at position id-1.
Recursive Calls – We know digit prev was filled at position id – 1. So for current position we will iterate for all digits from prev to 9. This will ensure that we are generating numbers such that their digits are in increasing order from left to right.
Memorization – It is easy to observe that we have overlapping sub-problems and optimal substructure. Now we can create a dp table and memoize our solution.
Time Complexity – O(10*n)
Space Complexity – O(10*n)
Code
Output
2
55
Login/Signup to comment