LeetCode 401 Binary Watch

来源:互联网 发布:淘宝商品质量问题退钱 编辑:程序博客网 时间:2024/06/11 06:50

题目:

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"]

Note:

  • The order of output does not matter.
  • The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
  • The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".

题目链接

题意:

有一种手表,它的时钟和分钟都是用二进制表示的,当表示某一位的灯亮,说明该位为1,否则为0,现给出所有量亮的数,问所有可能的时间,返回所有可能时间的vector。

使用递归搜索的方法,注意hour的范围0~11,minute的范围0~59,且minute位数不足两位用前置0来补齐。

代码如下:

class Solution {public:    set<string> ans;    void timeToString(int *a) {        string sMinute;        int hour = a[0] + a[1] * 2 + a[2] * 4 + a[3] * 8;        if (hour > 11) return;        int minute = a[4] + a[5] * 2 + a[6] * 4 + a[7] * 8 + a[8] * 16 + a[9] * 32;        if (minute > 59) return;        else if (minute < 10) {            sMinute = "0" + to_string(minute);        }        else            sMinute = to_string(minute);        ans.insert(to_string(hour) + ":" + sMinute);    }    void solve(int *a, int now, int n) {        if (now == n) {            timeToString(a);            return;        }        for (int i = 0; i < 10; i++) {            if (!a[i]) {                a[i] = 1;                solve(a, now + 1, n);                a[i] = 0;            }        }    }    vector<string> readBinaryWatch(int num) {        int a[10];        memset(a, 0, sizeof a);        solve(a, 0, num);        return vector<string>(ans.begin(), ans.end());    }};


原创粉丝点击