Leetcode 401:二进制手表

二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。

每个 LED 代表一个 0 或 1,最低位在右侧。

例如,上面的二进制手表读取 “3:25”。

给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。

案例:

输入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
 

注意事项:

输出的顺序没有要求。
小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-watch
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

马上农历新年啦!边刷Leetcode边等春晚。

class Solution {
public:
    vector<string> ans;
    void dfs(string &str,int cur,int num){
        if(num==0){
            int minute=(str[0]-'0')*1+(str[1]-'0')*2+(str[2]-'0')*4+(str[3]-'0')*8+(str[4]-'0')*16+(str[5]-'0')*32;
            int hour=(str[6]-'0')*1+(str[7]-'0')*2+(str[8]-'0')*4+(str[9]-'0')*8;
            if(hour>=0&&hour<=11&&minute>=0&&minute<=59){
                string tmp=to_string(hour)+":";
                if(minute>=0&&minute<=9) tmp+="0"+to_string(minute);
                else tmp+=to_string(minute);
                ans.push_back(tmp);
            }
            return;
        }
        if(cur>=10) return;
        str[cur]='1';
        dfs(str,cur+1,num-1);
        str[cur]='0';
        dfs(str,cur+1,num);
    }
    vector<string> readBinaryWatch(int num) {
        string str="0000000000";
        dfs(str,0,num);
        return ans;
    }
};
发布了584 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/104081484
今日推荐