题目要求如下: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.
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".
解法一:
解题思路:将每一个小时中1出现的次数记录下来,比如3点,二进制是11,1出现了两次,用该位数作为key,把3转化成string记录进去;分钟类似;然后遍历num进行查找即可。
代码如下:
class Solution {
public:
int nums_1(int n){
int num = 0;
while(n){
num++;
n &= n-1;
}
return num;
}
vector<string> readBinaryWatch(int num) {
//整数存储亮的灯的个数,vector存储亮这些灯可能代表的时间的字符串
unordered_map<int,vector<string>> hours;
unordered_map<int,vector<string>> minus;
vector<string> result;
for(int i = 0 ; i<12 ; i++){
hours[nums_1(i)].push_back(to_string(i));
}
for(int i = 0 ; i<10 ; i++){
minus[nums_1(i)].push_back("0"+to_string(i));
}
for(int i = 10; i<60 ; i++){
minus[nums_1(i)].push_back(to_string(i));
}
for(int i = 0; i<=3 && i<= num ; i++){
if(num - i >=6) continue;
int len_h = hours[i].size();
int len_m = minus[num-i].size();
for(int j = 0; j < len_h ; j++){
for(int k = 0; k < len_m; k++){
string temp = hours[i][j] +":"+minus[num-i][k];
result.push_back(temp);
}
}
}
return result;
}
};
解法二:
解题思路:使用bitset统计hour和minute中出现1的此时的和,判断是否和num相等,如果相等,则放入结果中。
vector<string> readBinaryWatch(int num) {
vector<string> rs;
for (int h = 0; h < 12; h++)
for (int m = 0; m < 60; m++)
if (bitset<10>(h << 6 | m).count() == num)
rs.emplace_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m));
return rs;
}
解法三:回溯法