leetcode-401 二进制手表
题目描述:
二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。每个 LED 代表一个 0 或 1,最低位在右侧。给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。
参考:负雪明烛
from itertools import combinations
class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
def dfs(num,hour,res):
if hour > num: return
for hours in combinations([1,2,4,8],hour):
hs = sum(hours)
if hs >= 12: continue
for mints in combinations([1,2,4,8,16,32],num-hour):
ms = sum(mints)
if ms >= 60: continue
res.append("%d:%02d"%(hs,ms))
dfs(num,hour+1,res)
res = []
dfs(num,0,res)
return res
参考:panda爱学习
from itertools import combinations
class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
res = []
for h in range(12):
for m in range(60):
if (bin(h)+bin(m)).count('1') == num:
res.append("%d:%02d"%(h,m))
return res