LeetCode 题解工作台
活字印刷
你有一套活字字模 tiles ,其中每个字模上都刻有一个字母 tiles[i] 。返回你可以印出的非空字母序列的数目。 注意: 本题中,每个活字字模只能使用一次。 示例 1: 输入: "AAB" 输出: 8 解释: 可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", …
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 回溯·pruning
答案摘要
我们先用一个哈希表或数组 统计每个字母出现的次数。 接下来定义一个函数 ,表示当前剩余字母的计数为 时,能够组成的不同序列的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
注意:本题中,每个活字字模只能使用一次。
示例 1:
输入:"AAB" 输出:8 解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。
示例 2:
输入:"AAABBC" 输出:188
示例 3:
输入:"V" 输出:1
提示:
1 <= tiles.length <= 7tiles由大写英文字母组成
解题思路
方法一:计数 + 回溯
我们先用一个哈希表或数组 统计每个字母出现的次数。
接下来定义一个函数 ,表示当前剩余字母的计数为 时,能够组成的不同序列的个数。
在 中,我们枚举 中每个大于 的值 ,将 减 表示使用了这个字母,序列个数加 ,然后进行下一层搜索,在搜索结束后,累加返回的序列个数,然后将 加 。最后返回序列个数。
时间复杂度 ,空间复杂度 。其中 为字母种类数。
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
def dfs(cnt: Counter) -> int:
ans = 0
for i, x in cnt.items():
if x > 0:
ans += 1
cnt[i] -= 1
ans += dfs(cnt)
cnt[i] += 1
return ans
cnt = Counter(tiles)
return dfs(cnt)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(2^n * n) because each subset of tiles may generate sequences up to length n, and space complexity is O(2^n * n) due to storing counts during recursion. |
| 空间 | O(2^n \cdot n) |
面试官常问的追问
外企场景- question_mark
Pay attention to duplicate letters and avoid counting identical sequences multiple times.
- question_mark
Consider using a hash map for tracking available letters instead of generating permutations blindly.
- question_mark
Focus on pruning paths early to keep recursion efficient for the maximum of 7 tiles.
常见陷阱
外企场景- error
Failing to account for duplicate letters, leading to overcounting sequences.
- error
Not decrementing letter counts correctly in recursion, causing incorrect sequence totals.
- error
Trying to generate all permutations explicitly instead of pruning with backtracking.
进阶变体
外企场景- arrow_right_alt
Count sequences allowing repeated usage of the same tile multiple times.
- arrow_right_alt
Find the lexicographically smallest sequence of a given length using the tiles.
- arrow_right_alt
Return all unique sequences instead of just counting them.