lintcode--二进制时间

时间:2025-03-27 13:58:36
class Solution { public: /* * @param : the number of "1"s on a given timetable * @return: all possible time */ vector<string> binaryTime(int num) { // Write your code here vector<int>watch; for(int i=0;i<10;i++){ watch.push_back(0); } vector<string>res; findtime(watch,res,0,num,0); return res; } void findtime(vector<int>&watch,vector<string>&res,int index,int num,int count) { if(count==num){//找到满足条件的时间,将其加入数组中 if(array_to_time(watch)!=""){ res.push_back(array_to_time(watch)); } return; } for(int i=index;i<10;i++){ watch[i]=1; findtime(watch,res,i+1,num,count+1); watch[i]=0; } } string array_to_time(vector<int>res) { int min=0; int hour=0; for(int i=0;i<6;i++){ min=min+pow(2,i)*res[i]; } for(int i=6;i<10;i++){ hour=hour+pow(2,i-6)*res[i]; } if(hour>=12||min>=60){//由于时间是在0:00--11:59之间,超过这个的就排除掉 string s=""; return s; } if(min<10){//由于分钟必须由两位数组成, 可能包含前导零,故min小于10时,我们需要在其前面加0 string s=""; s=s+to_string(hour)+":0"+to_string(min); return s; }else{ string s=""; s=s+to_string(hour)+":"+to_string(min); return s; } } void printvector(vector<int>res){ for(int i=0;i<();i++){ cout<<res[i]<<" "; } cout<<endl; } };