-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathconstruct-smallest-number-from-di-string.py
More file actions
43 lines (37 loc) · 1.37 KB
/
construct-smallest-number-from-di-string.py
File metadata and controls
43 lines (37 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution:
def smallestNumber(self, pattern: str) -> str:
stack: list[int] = []
seen: set[int] = set()
def dfs(pos: int) -> bool:
if pos == len(pattern):
return True
for num in range(1, 10):
if pattern[pos] == "I":
if stack[-1] + num < 10:
if stack[-1] + num in seen:
continue
seen.add(stack[-1] + num)
stack.append(stack[-1] + num)
if dfs(pos + 1):
return True
stack.pop()
seen.discard(stack[-1] + num)
else:
if stack[-1] - num > 0:
if stack[-1] - num in seen:
continue
seen.add(stack[-1] - num)
stack.append(stack[-1] - num)
if dfs(pos + 1):
return True
stack.pop()
seen.discard(stack[-1] - num)
return False
for num in range(1, 10):
stack.append(num)
seen.add(num)
if dfs(0):
break
stack.pop()
seen.discard(num)
return "".join(map(str, stack))