LeetCode 题解工作台
二进制手表
二进制手表顶部有 4 个 LED 代表 小时(0-11) ,底部的 6 个 LED 代表 分钟(0-59) 。每个 LED 代表一个 0 或 1,最低位在右侧。 例如,下面的二进制手表读取 "4:51" 。 给你一个整数 turnedOn ,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 回溯·pruning
答案摘要
题目可以转换为求 $i \in [0, 12)$ 和 $j \in [0, 60)$ 的所有可能组合。 合法组合需要满足的条件是 的二进制形式中 1 的个数加上 的二进制形式中 1 的个数,结果等于 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)。每个 LED 代表一个 0 或 1,最低位在右侧。
- 例如,下面的二进制手表读取
"4:51"。

给你一个整数 turnedOn ,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所有可能时间。你可以 按任意顺序 返回答案。
小时不会以零开头:
- 例如,
"01:00"是无效的时间,正确的写法应该是"1:00"。
分钟必须由两位数组成,可能会以零开头:
- 例如,
"10:2"是无效的时间,正确的写法应该是"10:02"。
示例 1:
输入:turnedOn = 1 输出:["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
示例 2:
输入:turnedOn = 9 输出:[]
提示:
0 <= turnedOn <= 10
解题思路
方法一:枚举组合
题目可以转换为求 和 的所有可能组合。
合法组合需要满足的条件是 的二进制形式中 1 的个数加上 的二进制形式中 1 的个数,结果等于 。
时间复杂度 ,空间复杂度 。
class Solution:
def readBinaryWatch(self, turnedOn: int) -> List[str]:
return [
'{:d}:{:02d}'.format(i, j)
for i in range(12)
for j in range(60)
if (bin(i) + bin(j)).count('1') == turnedOn
]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for an understanding of backtracking and how it can be applied to the problem.
- question_mark
Check for familiarity with bit manipulation and its role in efficiently solving problems with binary representations.
- question_mark
Ensure the candidate is aware of edge cases, such as when turnedOn is 9 (impossible configuration).
常见陷阱
外企场景- error
Failing to handle edge cases like impossible configurations where turnedOn is too large to form a valid time.
- error
Not properly handling leading zeros in the hour component.
- error
Overcomplicating the solution by not utilizing bit manipulation and pruning effectively, leading to inefficiency.
进阶变体
外企场景- arrow_right_alt
Consider optimizing the solution for different input ranges, such as turnedOn being larger than 10.
- arrow_right_alt
Modify the problem to generate only times that are specific to a given hour or minute range.
- arrow_right_alt
Adapt the problem to include time intervals or add additional constraints, such as ensuring the time is within a certain range.