![]() |
VOOZH | about |
Given two integers n and sum, find the number of n-digit positive integers whose digits add up to sum.
Example:
Input: n = 2, sum= 2
Output: 2
Explanation: The numbers are 11 and 20 .Input: n = 1, sum = 10
Output: -1
Explanation: A single-digit number can only have a digit sum between 0 and 9.Input: n = 2, sum= 5
Output: 5
Explanation: The numbers are 14, 23, 32, 41 and 50.
Table of Content
The idea is to use recursion to try every digit from 0 to 9 for each position, reducing the given sum at each step. The first digit is taken from 1 to 9 to ensure valid n-digit numbers. The recursion stops when there are no digits left, checking if the sumbecomes zero.
5
We iterate through each number within the range of n-digit numbers. For each number, we calculate the sum of its digits. If the sum matches the given sum, we increment the count.
5
The idea is to count n-digit numbers with a sum of digits equal to the given sum using recursion with memoization to optimize repeated calculations.
5
The idea is to build the answer in a bottom-up manner using dynamic programming. We create a 2D DP table where dp[len][s] stores the number of ways to form a digit sequence of length len whose digits add up to s.
5