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".
方法一:枚举法,枚举小时和分钟的二进制位数,和是否等于num
class Solution {
public:
int countbit(int n){
int cnt=0;
while(n){
if(n%2){
cnt++;
}
n=n/2;
}
return cnt;
}
vector<string> readBinaryWatch(int num) {
int h,m;
vector<string>ans;
string s1,s2;
for(h=0;h<12;h++){
for(m=0;m<60;m++){
if((countbit(h)+countbit(m))==num){
s1=to_string(h);
s2=to_string(m);
if(m<10){
s2='0'+s2;
}
ans.push_back(s1+":"+s2);
}
}
}
return ans;
}
};
方法二:dfs
class Solution {
public:
vector<string>ans;
int timetable[10];
vector<string> readBinaryWatch(int num) {
dfs(0,0,num);
return ans;
}
void dfs(int index,int k,int num){
if(k==num){
change();
return ;//.....
}
if(index==10){//...
return;
}
timetable[index]=1;
dfs(index+1,k+1,num);
timetable[index]=0;
dfs(index+1,k,num);
}
void change(){
int i,h=0,m=0;
for(i=0;i<4;i++){
if(timetable[i]==1){
h=h+(int)pow(2,i);
}
}
for(i=4;i<10;i++){
if(timetable[i]==1){
m=m+(int)pow(2,i-4);
}
}
if(h<=11&&m<=59){
string hour=to_string(h);
string minute=to_string(m);
if(m<10){
minute="0"+minute;
}
ans.push_back(hour+":"+minute);
}
}
};