401. 二进制手表

二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。每个 LED 代表一个 0 或 1,最低位在右侧。

 

例如,上面的二进制手表读取 “3:25”。

给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。

案例:

输入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

class Solution:
    def readBinaryWatch(self, num: int) -> List[str]:
        hour = [1, 2, 4, 8]
        minute = [1, 2, 4, 8, 16, 32]
        result = []
        def backtrack(path, h, m, n): #回溯法
            # 结束条件
            if len(path) == n:
                if h < 12 and m < 60:
                    if m < 10:
                        times = str(h) + ':0' + str(m)
                    else:
                        times = str(h) + ':' + str(m)
                    result.append(times)
                return
            for i in range(len(hour)+len(minute)):
                if i not in path:
                    if 0 <= i <= 3:
                        h += hour[i]
                        temp = hour[i]
                    elif 4 <= i <= 9:
                        m += minute[i-4]
                        temp = minute[i-4]
                    path.append(i)
                    backtrack(path, h, m, n)
                    path.pop()
                    if 0 <= i <= 3:
                        h -= temp
                    elif 4 <= i <= 9:
                        m -= temp
        backtrack([], 0, 0, num)
        return list(set(result))

  

posted @ 2020-04-19 16:40  USTC丶ZCC  阅读(230)  评论(0编辑  收藏  举报