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.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
- The order of output does not matter.
- The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
- The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
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"]
Python Solution:
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
if num > 8: return []
return ['{}:{:02d}'.format(h, m) for h in range(12) for m in range(60) if (bin(h) + bin(m)).count('1') == num]
C Solution:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void recu(int *ref, int start, int end, int bits, int num, char **res, int *returnSize) {
if (!num) {
int hour = bits >> 6;
int minute = bits & 0b111111;
if (hour > 11 || minute > 59) return;
char *s = malloc(6 * sizeof(char));
int p = sprintf(s, "%d", hour);
s[p++] = ':';
sprintf(s + p, "%02d", minute);
res[(*returnSize)++] = s;
return;
}
int i;
for (i = start; i < end; i++) {
bits |= ref[i];
recu(ref, i + 1, end, bits, num - 1, res, returnSize);
bits &= ~ref[i];
}
}
char** readBinaryWatch(int num, int* returnSize) {
if (num > 8) return 0;
char **res = malloc(720 * sizeof(char *));
*returnSize = 0;
int ref[10] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
int bits = 0;
recu(ref, 0, 10, bits, num, res, returnSize);
return res;
}
Summary:
- Consider the size of the problem, if it's fixed and small, brute-force maybe a good choice.
LeetCode: 401. Binary Watch
近期评论