401 Binary Watch

401. Binary Watch

1. Question

A binary watch has 4 LEDs on the top which represent thehours(0-11), and the 6 LEDs on the bottom represent theminutes(0-59).
Each LED represents a zero or one, with the least significant bit on the right.
Could not load image
For example, the above binary watch reads "3:25".
Given a non-negative integernwhich represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
1
Input: n = 1
2
3
4
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Copied!
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".

2. Implementation

(1) Backtracking
思路: 根据给定的输入num,我们生成所有可能的hours和minutes值,其中要注意排除无效的值,比如hours必须小于12,minutes必须小于60
1
public class Solution {
2
/*
3
* Given a num, find the combination from hours array {8, 4, 2, 1}
4
* and minutes array {32, 16, 8, 4, 2, 1}
5
*/
6
public List<String> readBinaryWatch(int num) {
7
List<String> res = new ArrayList<>();
8
int[] hours = {8, 4, 2, 1};
9
int[] minutes = {32, 16, 8, 4, 2, 1};
10
11
for (int i = 0; i <= num; i++) {
12
// Get i elements from hours array and the remaining (num - i) from minutes
13
List<Integer> hoursList = generateDigit(hours, i, 12);
14
List<Integer> minutesList = generateDigit(minutes, num - i, 60);
15
for (int hour : hoursList) {
16
for (int min : minutesList) {
17
// Convert digit to correct time form
18
res.add(hour + ":" + (min < 10 ? "0" + min : min));
19
}
20
}
21
}
22
return res;
23
}
24
25
public List<Integer> generateDigit(int[] nums, int count, int max) {
26
List<Integer> res = new ArrayList<>();
27
recGenerateDigit(nums, count, 0, 0, max, res);
28
return res;
29
}
30
31
public void recGenerateDigit(int[] nums, int count, int pos, int sum, int max, List<Integer> res) {
32
// Exclude invalid value of hour (>= 12) and minute (>= 60)
33
if (sum >= max) {
34
return;
35
}
36
37
if (count == 0) {
38
res.add(sum);
39
return;
40
}
41
42
for (int i = pos; i < nums.length; i++) {
43
recGenerateDigit(nums, count - 1, i + 1, sum + nums[i], max, res);
44
}
45
}
46
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(12 * 60) => O(1), 空间复杂度O(12 * 60) => O(1)