PROBLEM:
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".
SOLVE:
class Solution {
public:
vector<string> readBinaryWatch(int num) {
//pay attention to 60~63 of minite and 12~15 of hour
vector<string> res;
int h = 0, m = 0;
vector<vector<int>> hourKind = kindOfhour();
vector<vector<int>> minKind = kindOfmin();
for (int i = 0;i <= 4 && i <= num;++i) {
//i is count of hour LED, j is count of min LED, should promise 0<=i<=4 & 0<=j<=6
int j = num - i;
if (j > 6) continue; //num may be 7,8,9,10, it will cause wrong when i equal to 0
for (int h : hourKind[i])
for (int m : minKind[j])
res.push_back(numToTime(h, m));
}
return res;
}
private:
string numToTime(int h, int m) {
//transform (h,m) to string in the form of "X:XX"
string res;
res = to_string(h) + ":";
if (m<10)
res = res + '0' + to_string(m);
else
res += to_string(m);
return res;
}
vector<vector<int>> kindOfhour(void) {
//res[i],i is the num of LED, res[i] consist of all impossible hours
vector<vector<int>> res(5, vector<int>());
for (int i = 0;i<12;i++) {
int Index = 0;
for (int tmp = i;tmp>0;tmp = tmp >> 1)
if (tmp % 2 == 1)
Index++;
res[Index].push_back(i);
}
return res;
}
vector<vector<int>> kindOfmin(void) {
//res[i],i is the num of LED, res[i] consist of all impossible minitues
vector<vector<int>> res(7, vector<int>());
for (int i = 0;i<60;i++) {
int Index = 0;
for (int tmp = i;tmp>0;tmp = tmp >> 1)
if (tmp % 2 == 1)
Index++;
res[Index].push_back(i);
}
return res;
}
};
分析:这里一个技巧是在求n个LED时可能的组合数,反过来对组合数遍历,放入对应LED组合中。