Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
Example
Input: n = 1
Return: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]
Solution
@高效的暴力搜索
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
ret = []
for i in range(12):
for j in range(60):
if bin(i).count('1')+bin(j).count('1')== num:
ret.append('%d:%02d'%(i,j))
return ret
@DFS写法失败了 待研究 https://leetcode.com/problems/binary-watch/
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
self.hour_list = [1,2,4,8,16,32]
ret = []
if num>=8:
return ret
for i in range(min(4,num+1)):
self.generate(i, num-i, 0, 0, ret)
return ret
def generate(self, hour, minute, hour_value, minute_value, ret):
if hour==0 and minute==0:
if hour_value>=12 or minute_value>=60:
return
if minute_value<10:
retstr = str(hour_value)+':0'+str(minute_value)
else:
retstr = str(hour_value)+':'+str(minute_value)
if retstr in ret:
return
ret.append(retstr)
return
if hour>0:
for i in range(4):
self.generate(hour-1, minute, hour_value+self.hour_list[i], minute_value, ret)
if minute>0:
for i in range(6):
self.generate(hour, minute-1, hour_value, minute_value+self.hour_list[i], ret)