leetcode 401: 二进制手表

题目描述

思路

思路一:递归回溯 使用一个长度为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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值