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”]
请点击:题目链接打开leetcode原始 链接
#include <iostream>
#include <vector>
#include<string>
#include<sstream>
#include <algorithm>
#include<math.h>
#include<limits.h>
using namespace std;
string int2str(int a,int b){
stringstream ss;
ss.clear();
ss<<a;
ss<<":";
if(b<10) ss<<"0"<<b;
else ss<<b;
string s;
ss>>s;
return s;
}
void f(vector<string> & sol,string s,int N,int sta,int leftnum){
// N是s的长度,sta表从s的第sta位开始考虑,leftnum表s[sta]~s[end]之间有leftnum个亮灯的位置
if(N-sta<leftnum) return;
if(leftnum==0) {sol.push_back(s);return;}
f(sol,s,N,sta+1,leftnum);//递归分支1:s[sta]不亮
s[sta]='1';
f(sol,s,N,sta+1,leftnum-1);//递归分支2:s[sta]亮
}
vector<int> getpossibleSol(int N,int i){
//N个灯,亮i个,---》 返回所有可能的情况
if(i>N) cout<<"err"<<endl;
string s(N,'0');
vector<string> sol;//N=4,i=1时,所有可能情况0001,0010,0100,1000
vector<int> solint;//将sol中的每种可能转化为int数字,1,2,4,8
f(sol,s,N,0,i);//生成所有的从N个数中选i个的可能,保存在sol中
for(int j=0;j<sol.size();j++){
int sum=0;
for(int k=0;k<N;k++){
sum+=( pow(2,N-1-k)*(sol[j][k]-'0') );
}
solint.push_back(sum);
}
return solint;
}
int main(){
int n;//led灯亮的个数
cin>>n;
int N(4),M(6);
vector<int> sola,solb;
vector<string> sol;
for(int i=0;i<=n && i<=4;i++){//i表示第一行led亮多少个
int j=n-i;//j表示第2行led亮多少个
sola.clear();
solb.clear();
sola=getpossibleSol(N,i);//第一行4个灯,亮i个,所有可能的情况包含在sola中
solb=getpossibleSol(M,j);
for(int ii=0;ii<sola.size();ii++){
for(int jj=0;jj<solb.size();jj++){
if(sola[ii]<12 && solb[jj]<60)
sol.push_back(int2str(sola[ii],solb[jj]));
}
}
}
for(int i=0;i<sol.size();i++){
cout<<sol[i]<<endl;
}
system("pause");
return 0;
}