题目

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.
image.png
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:

  1. Input: n = 1
  2. 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”.

题意

一个特立独行的手表,用二进制位来表示时间。4位表示小时,6位表示分钟。求在10位中选出n位一共可以得到的时间组合。

思路

回溯法。需要注意其中的坑:小时最大值只能为11,分钟最大值只能为59。

另一种暴力法是,小时数只有12种可能,分钟数只有60种可能,直接暴力搜索每一种组合,判断它们二进制1的位数相加是否为n。


代码实现

Java

回溯法

  1. class Solution {
  2. public List<String> readBinaryWatch(int num) {
  3. List<String> ans = new ArrayList<>();
  4. int[] available = { 1, 2, 4, 8, 101, 102, 104, 108, 116, 132 };
  5. dfs(num, new int[2], available, 0, ans);
  6. return ans;
  7. }
  8. private void dfs(int num, int[] time, int[] available, int index, List<String> ans) {
  9. if (num == 0) {
  10. ans.add(time[0] + ":" + (time[1] < 10 ? "0" + time[1] : time[1]));
  11. return;
  12. }
  13. if (index == 10) {
  14. return;
  15. }
  16. if (available[index] > 100 && time[1] + available[index] - 100 < 60) {
  17. time[1] += available[index] - 100;
  18. dfs(num - 1, time, available, index + 1, ans);
  19. time[1] -= available[index] - 100;
  20. } else if (available[index] < 100 && time[0] + available[index] < 12) {
  21. time[0] += available[index];
  22. dfs(num - 1, time, available, index + 1, ans);
  23. time[0] -= available[index];
  24. }
  25. dfs(num, time, available, index + 1, ans);
  26. }
  27. }

暴力法

  1. class Solution {
  2. public List<String> readBinaryWatch(int num) {
  3. List<String> ans = new ArrayList<>();
  4. for (int h = 0; h < 12; h++) {
  5. for (int m = 0; m < 60; m++) {
  6. if (countOne(h) + countOne(m) == num) {
  7. ans.add(h + ":" + (m < 10 ? "0" + m : m));
  8. }
  9. }
  10. }
  11. return ans;
  12. }
  13. private int countOne(int num) {
  14. int count = 0;
  15. while (num != 0) {
  16. if ((num & 1) == 1) {
  17. count++;
  18. }
  19. num >>= 1;
  20. }
  21. return count;
  22. }
  23. }