题目描述
思路
思路一:递归回溯 使用一个长度为10的数组进行组合编码,最终输出时间
思路二:两重for循环分别代表小时和分钟
代码
class Solution {
public:
vector<string> res;
string temp;
void dfs(vector<int> led, int num,int index)
{
if(num==0)
{
int hour,min;
//解码
hour = led[0]*8 +led[1]*4+led[2]*2+led[3]*1;
min = led[4]*32+led[5]*16+led[6]*8+led[7]*4+led[8]*2
+led[9]*1;
if(hour<12&&min<60)
{
temp = to_string(hour)+ (min<10?":0":":") +to_string(min);
res.push_back(temp);
}
}
for(int i=index;i<led.size();i++)
{
led[i]++;
dfs(led,num-1,i+1);
led[i]--;
}
}
vector<string> readBinaryWatch(int num) {
vector<int> led(10,0);
dfs(led,num,0);
return res;
}
};
class Solution {
public:
vector<string> readBinaryWatch(int num) {
vector<string> ret;
for(int i=0;i<12;i++)
{
bitset<4> hour(i); //小时
for(int j=0;j<60;j++)
{
bitset<6> min(j); //分钟
if(hour.count()+min.count() == num)
{
ret.push_back(to_string(i)+(j<10?":0":":")+to_string(j));
}
}
}
return ret;
}
};
重难点分析
1. bitset
bitset<8> ex(5); //表示长度为8位,以十进制5初始化,所以为0000 1001
//当然bitset也支持 "0001" 初始化,高位补0
2.count1
//bitset可以用count 1代替
void countOne(int n)
{
int count = 0;
while(n)
{
count++;
n = (n-1)&n;
}
return count;
}