题目描述:
401. Binary Watch
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".
解题思路:
由于一共有十盏灯,给出一个数n,枚举出所有n盏灯可能的情况。首先将10盏灯编号,然后根据n,生成n组合。代码中generate_Comb即为生成组合的函数,通过这种枚举的方法,判断所代表的时间是否合法(0=<h=<11,0=<m<=59),将合法答案加入ans中即可。
代码展示:
class Solution {
public:
void generate_Comb(vector<int>&tmp,int n,int r )
{
int i=r;
while(tmp[i]==n-r+i)
{
i--;
}
tmp[i]++;
for(int j=i+1;j<=r;j++)
{
tmp[j]=tmp[i]+j-i;
}
}
string ntoh(int n)
{
string ans = "";
if(n==0)
{
ans="0";
return ans;
}
while(n>0)
{
ans = char(n%10+'0')+ans;
n/=10;
}
return ans;
}
string ntom(int n)
{
bool flag = false;
if(n<10)
flag = true;
string ans = "";
if(n==0)
{
ans="00";
return ans;
}
while(n>0)
{
ans = char(n%10+'0')+ans;
n/=10;
}
if(flag) return "0"+ans;
return ans;
}
void cal_time(vector<string>&res,vector<int>tmp)
{
int h=0;
int m=0;
for(int i=1;i<tmp.size();i++)
{
if(tmp[i]<=4)
{
h+=(1<<(tmp[i]-1));
if(h>11) return;
}
else
{
m+=(1<<(tmp[i]-4-1));
if(m>59) return;
}
}
res.push_back(ntoh(h)+":"+ntom(m));
return;
}
vector<string> readBinaryWatch(int num) {
vector<string> ans;
if(num==0)
{
ans.push_back("0:00");
return ans;
}
vector<int> tmp;
tmp.push_back(0);
for(int i=1;i<=num;i++)
tmp.push_back(i);
cal_time(ans,tmp);
int numofloop = 1;
int dw = 1;
int up =1;
for(int i=1;i<=num;i++)
{
dw*=i;
}
for(int i=1;i<=num;i++)
{
up*=(10-i+1);
}
numofloop = up/dw;
while(--numofloop)
{
generate_Comb(tmp,10,num );
cal_time(ans,tmp);
}
return ans;
}
};