Given an positive integer n. Count the different numbers that can be generated using digits 1, 2, 3 and 4 such that digits sum is the number ‘n’. Here digit ‘4’ will be treated as ‘1’. For instance,
32 = 3 + 2 = 5
1341 = 1 + 3 + 1 + 1 = 6
441 = 1 + 1 + 1 = 3
Note: Answer the value in mod = 109+7
Input: 2 Output: 5 Explanation There are only '5' numbers that can be made: 11 = 1 + 1 = 2 14 = 1 + 1 = 2 41 = 1 + 1 = 2 44 = 1 + 1 = 2 2 = 2 Input: 3 Output: 13 Explanation There are only '13' numbers that can be made i.e., 111, 114, 141, 144, 411, 414, 441, 444, 12, 21, 42, 24, 3.
The approach is to use Dynamic programming. The problem is same as coin change and Ways to write n as sum of two or more positive integers problems. The only difference is that, instead of iterating up-to ‘n’, iterate only from 1 to 3 as according to question, only 1, 2, 3 and 4 digits are allowed. But since ‘4’ can be replaced with ‘1’ therefore iterate through 1, 2 and 3 and double the count of ‘1’ for compensation of digit ‘4’.
Time complexity: O(n)
Auxiliary space: O(n)
Note: Asked in Directi coding round(2014 and 2017)
- Count of numbers whose sum of increasing powers of digits is equal to the number itself
- Count unique numbers that can be generated from N by adding one and removing trailing zeros
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Count numbers in given range such that sum of even digits is greater than sum of odd digits
- Find maximum product of digits among numbers less than or equal to N
- Count numbers with same first and last digits
- Count of numbers from range [L, R] whose sum of digits is Y
- Count numbers whose XOR with N is equal to OR with N
- Count of Numbers in Range where the number does not contain more than K non zero digits
- Count of N-digit numbers with all distinct digits
- Count different numbers possible using all the digits their frequency times
- Count of n digit numbers whose sum of digits equals to given sum
- Count Numbers with N digits which consists of odd number of 0's
- Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.