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.
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:
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".

2. Implementation

(1) Backtracking
思路: 根据给定的输入num,我们生成所有可能的hours和minutes值,其中要注意排除无效的值,比如hours必须小于12,minutes必须小于60
public class Solution {
/*
* Given a num, find the combination from hours array {8, 4, 2, 1}
* and minutes array {32, 16, 8, 4, 2, 1}
*/
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<>();
int[] hours = {8, 4, 2, 1};
int[] minutes = {32, 16, 8, 4, 2, 1};
for (int i = 0; i <= num; i++) {
// Get i elements from hours array and the remaining (num - i) from minutes
List<Integer> hoursList = generateDigit(hours, i, 12);
List<Integer> minutesList = generateDigit(minutes, num - i, 60);
for (int hour : hoursList) {
for (int min : minutesList) {
// Convert digit to correct time form
res.add(hour + ":" + (min < 10 ? "0" + min : min));
}
}
}
return res;
}
public List<Integer> generateDigit(int[] nums, int count, int max) {
List<Integer> res = new ArrayList<>();
recGenerateDigit(nums, count, 0, 0, max, res);
return res;
}
public void recGenerateDigit(int[] nums, int count, int pos, int sum, int max, List<Integer> res) {
// Exclude invalid value of hour (>= 12) and minute (>= 60)
if (sum >= max) {
return;
}
if (count == 0) {
res.add(sum);
return;
}
for (int i = pos; i < nums.length; i++) {
recGenerateDigit(nums, count - 1, i + 1, sum + nums[i], max, res);
}
}
}

3. Time & Space Complexity

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