leetcode 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”]
请点击:题目链接打开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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值