Leetcode401Binary Watch二进制手表

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

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

给定一个非负整数 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”。
class Solution {
public:
    vector<string> res;
    int visit[10];
    int visit2[60][60];
    int times[10];//从小到大
    vector<string> readBinaryWatch(int num)
    {
        if(num == 0)
        {
            res.push_back("0:00");
            return res;
        }
        int x = 1;
        for(int i = 0; i < 6; i++)
        {
            times[i] = x;
            x *= 2;
        }
        x = 1;
        for(int i = 6; i < 10; i++)
        {
            times[i] = x;
            x *= 2;
        }
        DFS(num, 0, 0);
        return res;
    }

    void DFS(int n, int h, int m)
    {
        if(n == 0)
        {
            if(visit2[h][m] == 1)
                return;
            string str = "";
            if(h == 0)
            {
                str = str + '0';
            }
            else
            {
                str = str + to_string(h);
            }
            str += ':';
            if(m == 0)
            {
                str = str + "00";
            }
            else if(m < 10)
            {
                str = str + '0' + to_string(m);
            }
            else
            {
                str = str + to_string(m);
            }
            res.push_back(str);
            visit2[h][m] = 1;
            return;
        }
        for(int i = 0; i < 10; i++)
        {
            if(visit[i] == 1)
                continue;
            if(i < 6)
            {
                if(m + times[i] > 59)
                    continue;
                visit[i] = 1;
                DFS(n - 1, h, m + times[i]);
                visit[i] = 0;
            }
            if(i >= 6)
            {
                if(h + times[i] > 11)
                    continue;
                visit[i] = 1;
                DFS(n - 1, h + times[i], m);
                visit[i] = 0;
            }
        }
    }
};
原文地址:https://www.cnblogs.com/lMonster81/p/10434099.html