401. Binary Watch
A binary watch has 4 LEDs on the top which represent thehours(0-11), and the 6 LEDs on the bottom represent theminutes(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 integernwhich represents the number of LEDs that are currently on, return all possible times the watch could represent.
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"]
Note:
- 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".
S1: backtracing & permutaion
dfs得到所有可能的hour和minus的组合
S2: bit manipulation
利用bitset找到可能的组合
vector<string> readBinaryWatch(int num) {
vector<string> result;
for (int hour = 0; hour < 12; ++hour) {
for (int minus = 0; minus < 60; ++minus) {
if (bitset<10>(hour << 6 | minus).count() == num) {
result.push_back(to_string(hour) + (minus < 10? ":0" : ":") + to_string(minus));
}
}
}
return result;
}