|
| 1 | +""" |
| 2 | +A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the |
| 3 | +minutes (0-59). |
| 4 | +
|
| 5 | +Each LED represents a zero or one, with the least significant bit on the right. |
| 6 | +
|
| 7 | +
|
| 8 | +For example, the above binary watch reads "3:25". |
| 9 | +
|
| 10 | +Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the |
| 11 | +watch could represent. |
| 12 | +
|
| 13 | +Example: |
| 14 | +
|
| 15 | +Input: n = 1 |
| 16 | +Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] |
| 17 | +Note: |
| 18 | +The order of output does not matter. |
| 19 | +The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". |
| 20 | +The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be |
| 21 | +"10:02". |
| 22 | +""" |
| 23 | +__author__ = 'Daniel' |
| 24 | + |
| 25 | + |
| 26 | +class Solution(object): |
| 27 | + def __init__(self): |
| 28 | + self.hours = (1, 2, 4, 8) |
| 29 | + self.minutes = (1, 2, 4, 8, 16, 32) |
| 30 | + |
| 31 | + def readBinaryWatch(self, num): |
| 32 | + """ |
| 33 | + orderly backtracking |
| 34 | +
|
| 35 | + :type num: int |
| 36 | + :rtype: List[str] |
| 37 | + """ |
| 38 | + def gen(): |
| 39 | + for hour_n in xrange(min(num, 4)+1): |
| 40 | + for hour in self.hour(hour_n): |
| 41 | + for minute in self.minute(num-hour_n): |
| 42 | + hour = str(hour) |
| 43 | + minute = ('0' + str(minute))[-2:] |
| 44 | + yield hour + ':' + minute |
| 45 | + |
| 46 | + return list(gen()) |
| 47 | + |
| 48 | + def gen(self, n, head, lst, func): |
| 49 | + if head == len(lst): |
| 50 | + yield None |
| 51 | + |
| 52 | + if n == 0: |
| 53 | + yield 0 |
| 54 | + |
| 55 | + for i in xrange(head, len(lst)): |
| 56 | + for rest in self.gen(n-1, i+1, lst, func): |
| 57 | + if rest is not None: |
| 58 | + ret = lst[i]+rest |
| 59 | + if func(ret): |
| 60 | + yield ret |
| 61 | + else: |
| 62 | + break |
| 63 | + |
| 64 | + def hour(self, n): |
| 65 | + return self.gen(n, 0, self.hours, lambda x: x < 12) |
| 66 | + |
| 67 | + def minute(self, n): |
| 68 | + return self.gen(n, 0, self.minutes, lambda x: x < 60) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + assert Solution().readBinaryWatch(1) == ['0:01', '0:02', '0:04', '0:08', '0:16', '0:32', '1:00', '2:00', '4:00', |
| 73 | + '8:00'] |
0 commit comments