LeetCode 题解工作台

二进制手表

二进制手表顶部有 4 个 LED 代表 小时(0-11) ,底部的 6 个 LED 代表 分钟(0-59) 。每个 LED 代表一个 0 或 1,最低位在右侧。 例如,下面的二进制手表读取 "4:51" 。 给你一个整数 turnedOn ,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 回溯·pruning

bolt

答案摘要

题目可以转换为求 $i \in [0, 12)$ 和 $j \in [0, 60)$ 的所有可能组合。 合法组合需要满足的条件是 的二进制形式中 1 的个数加上 的二进制形式中 1 的个数,结果等于 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

二进制手表顶部有 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
lightbulb

解题思路

方法一:枚举组合

题目可以转换为求 i[0,12)i \in [0, 12)j[0,60)j \in [0, 60) 的所有可能组合。

合法组合需要满足的条件是 ii 的二进制形式中 1 的个数加上 jj 的二进制形式中 1 的个数,结果等于 turnedOn\textit{turnedOn}

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
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
        ]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

二进制手表题解:回溯·pruning | LeetCode #401 简单