Given two integers ‘n’ and ‘sum’, find count of all n digit numbers with sum of digits as ‘sum’. Leading 0’s are not counted as digits.
1 <= n <= 100 and 1 <= sum <= 50000
Example:
Input: n = 2, sum = 2 Output: 2 Explanation: Numbers are 11 and 20 Input: n = 2, sum = 5 Output: 5 Explanation: Numbers are 14, 23, 32, 41 and 50 Input: n = 3, sum = 6 Output: 21
The idea is simple, we subtract all values from 0 to 9 from given sum and recur for sum minus that digit. Below is recursive formula.
countRec(n, sum) = ∑countRec(n-1, sum-x) where 0 =< x <= 9 and sum-x >= 0 One important observation is, leading 0's must be handled explicitly as they are not counted as digits. So our final count can be written as below. finalCount(n, sum) = ∑countRec(n-1, sum-x) where 1 =< x <= 9 and sum-x >= 0[ad type=”banner”]
Below is a simple recursive solution based on above recursive formula.
Output:
5
The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. For example, if we start with n = 3 and sum = 10, we can reach n = 1, sum = 8, by considering digit sequences 1,1 or 2, 0.
Since same suproblems are called again, this problem has Overlapping Subprolems property. So min square sum problem has both properties of a dynamic programming problem.
Below is Memoization based the implementation.
Output:
5[ad type=”banner”]