LeetCode 题解工作台

活字印刷

你有一套活字字模 tiles ,其中每个字模上都刻有一个字母 tiles[i] 。返回你可以印出的非空字母序列的数目。 注意: 本题中,每个活字字模只能使用一次。 示例 1: 输入: "AAB" 输出: 8 解释: 可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", …

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 回溯·pruning

bolt

答案摘要

我们先用一个哈希表或数组 统计每个字母出现的次数。 接下来定义一个函数 ,表示当前剩余字母的计数为 时,能够组成的不同序列的个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。

注意:本题中,每个活字字模只能使用一次。

 

示例 1:

输入:"AAB"
输出:8
解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。

示例 2:

输入:"AAABBC"
输出:188

示例 3:

输入:"V"
输出:1

 

提示:

  • 1 <= tiles.length <= 7
  • tiles 由大写英文字母组成
lightbulb

解题思路

方法一:计数 + 回溯

我们先用一个哈希表或数组 cntcnt 统计每个字母出现的次数。

接下来定义一个函数 dfs(cnt)dfs(cnt),表示当前剩余字母的计数为 cntcnt 时,能够组成的不同序列的个数。

dfsdfs 中,我们枚举 cntcnt 中每个大于 00 的值 cnt[i]cnt[i],将 cnt[i]cnt[i]11 表示使用了这个字母,序列个数加 11,然后进行下一层搜索,在搜索结束后,累加返回的序列个数,然后将 cnt[i]cnt[i]11。最后返回序列个数。

时间复杂度 O(n×n!)O(n \times n!),空间复杂度 O(n)O(n)。其中 nn 为字母种类数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

活字印刷题解:回溯·pruning | LeetCode #1079 中等