LeetCode 题解工作台
根据模式串构造最小数字
给你下标从 0 开始、长度为 n 的字符串 pattern ,它包含两种字符, 'I' 表示 上升 , 'D' 表示 下降 。 你需要构造一个下标从 0 开始长度为 n + 1 的字符串,且它要满足以下条件: num 包含数字 '1' 到 '9' ,其中每个数字 至多 使用一次。 如果 patter…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
定义 ,其中 表示当前答案字符串的长度。从 开始搜索,直至找到第一个符合条件的字符串。 时间复杂度 ,空间复杂度 。其中 表示字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给你下标从 0 开始、长度为 n 的字符串 pattern ,它包含两种字符,'I' 表示 上升 ,'D' 表示 下降 。
你需要构造一个下标从 0 开始长度为 n + 1 的字符串,且它要满足以下条件:
num包含数字'1'到'9',其中每个数字 至多 使用一次。- 如果
pattern[i] == 'I',那么num[i] < num[i + 1]。 - 如果
pattern[i] == 'D',那么num[i] > num[i + 1]。
请你返回满足上述条件字典序 最小 的字符串 num。
示例 1:
输入:pattern = "IIIDIDDD" 输出:"123549876" 解释: 下标 0 ,1 ,2 和 4 处,我们需要使 num[i] < num[i+1] 。 下标 3 ,5 ,6 和 7 处,我们需要使 num[i] > num[i+1] 。 一些可能的 num 的值为 "245639871" ,"135749862" 和 "123849765" 。 "123549876" 是满足条件最小的数字。 注意,"123414321" 不是可行解因为数字 '1' 使用次数超过 1 次。
示例 2:
输入:pattern = "DDD" 输出:"4321" 解释: 一些可能的 num 的值为 "9876" ,"7321" 和 "8742" 。 "4321" 是满足条件最小的数字。
提示:
1 <= pattern.length <= 8pattern只包含字符'I'和'D'。
解题思路
方法一:DFS
定义 ,其中 表示当前答案字符串的长度。从 开始搜索,直至找到第一个符合条件的字符串。
时间复杂度 ,空间复杂度 。其中 表示字符串 的长度。
class Solution:
def smallestNumber(self, pattern: str) -> str:
def dfs(u):
nonlocal ans
if ans:
return
if u == len(pattern) + 1:
ans = ''.join(t)
return
for i in range(1, 10):
if not vis[i]:
if u and pattern[u - 1] == 'I' and int(t[-1]) >= i:
continue
if u and pattern[u - 1] == 'D' and int(t[-1]) <= i:
continue
vis[i] = True
t.append(str(i))
dfs(u + 1)
vis[i] = False
t.pop()
vis = [False] * 10
t = []
ans = None
dfs(0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate an understanding of stack-based algorithms and how they can be used for state management in this context.
- question_mark
Look for a clear explanation of the greedy approach, ensuring that the candidate can justify how it minimizes the lexicographical order.
- question_mark
The candidate should efficiently explain the time and space complexity of their solution, ensuring that they are aware of the optimal performance for this problem.
常见陷阱
外企场景- error
Forgetting to pop the stack when encountering an 'I' pattern may result in an incorrect number sequence.
- error
Incorrect handling of 'I' and 'D' patterns could lead to not achieving the smallest lexicographical number.
- error
Not managing the stack properly may lead to inefficient space or time complexity, making the solution suboptimal.
进阶变体
外企场景- arrow_right_alt
Handling larger inputs with longer patterns can add complexity, though the algorithm remains O(n) in time and space.
- arrow_right_alt
If the pattern is all 'I' or all 'D', the stack's behavior changes, but the approach still applies with minimal modification.
- arrow_right_alt
The pattern length could affect the stack usage and result in different behavior, so optimizing space usage in the stack could be a potential focus.