Skip to content

Commit d9a484d

Browse files
authored
Added digit_dp problem with python solution
1 parent 5d2eb02 commit d9a484d

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

digit_dp.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Problem Link -: https://leetcode.com/problems/numbers-at-most-n-given-digit-set/
2+
# Problem -: Numbers At Most N Given Digit Set
3+
# Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
4+
# Return the number of positive integers that can be generated that are less than or equal to a given integer n.
5+
6+
7+
8+
# Python Digit DP Solution
9+
def atMostNGivenDigitSet(self, D: List[str], N: int) -> int:
10+
D = list(map(int, D))
11+
N = list(map(int, str(N)))
12+
13+
@functools.lru_cache(None)
14+
def dp(i, isPrefix, isBigger):
15+
if i == len(N):
16+
return not isBigger
17+
if not isPrefix and not isBigger:
18+
return 1 + len(D) * dp(i + 1, False, False)
19+
return 1 + sum(dp(i + 1, isPrefix and d == N[i], isBigger or (isPrefix and d > N[i])) for d in D)
20+
21+
return dp(0, True, False) - 1

0 commit comments

Comments
 (0)