Problem
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order.
The hour must not contain a leading zero.
- For example, “01:00” is not valid. It should be “1:00”.
The minute must consist of two digits and may contain a leading zero.
- For example, “10:2” is not valid. It should be “10:02”.
Algorithm
Count the state of the LED and sum them in hours and minutes.
Code
class Solution:def readBinaryWatch(self, turnedOn: int) -> List[str]:hours_minutes = [8, 4, 2, 1, 32, 16, 8, 4, 2, 1] # 4 + 6buf = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]ans = []def dfs(n, s):if not n:h, m = 0, 0for i in range(4):h += hours_minutes[i] * buf[i]for i in range(4, 10):m += hours_minutes[i] * buf[i]if h >= 0 and h <= 11 and m >= 0 and m <= 59:ans.append(str(h)+":"+str(m//10)+str(m%10))returnelse:for i in range(s, 10):buf[i] = 1dfs(n-1, i+1)buf[i] = 0dfs(turnedOn, 0)return ans