Skip to content

Commit 0e53d73

Browse files
committed
Time: 7 ms (100%), Space: 18 MB (41.67%) - LeetHub
1 parent 4b97c60 commit 0e53d73

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
class Solution:
4+
def countDistinct(self, n: int) -> int:
5+
s = str(n)
6+
L = len(s)
7+
8+
total = 0
9+
for length in range(1, L):
10+
total += 9 ** length
11+
12+
dp = [[0] * 2 for _ in range(L + 1)]
13+
14+
dp[L][0] = 1
15+
dp[L][1] = 1
16+
17+
for i in range(L - 1, -1, -1):
18+
limit = int(s[i])
19+
for tight in (0, 1):
20+
maxDigit = limit if tight else 9
21+
result = 0
22+
for dig in range(1, maxDigit + 1):
23+
newTight = tight and (dig == maxDigit)
24+
result += dp[i + 1][newTight]
25+
dp[i][tight] = result
26+
27+
total += dp[0][1]
28+
return total
29+
30+
31+
n = 10
32+
print(Solution().countDistinct(n))
33+
n = 3
34+
print(Solution().countDistinct(n))

0 commit comments

Comments
 (0)