401. Binary Watch
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".
My Solutions:
用backtracking的思想,把所有时针分钟有可能的答案找到,再组合起来
class Solution {
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<>();
int[] hours = new int[]{1,2,4,8};
int[] mins = new int[]{1,2,4,8,16,32};
if (num > 10 || num < 0) return res;
for (int i = 0; i <= num; i++) {
List<Integer> l1 = generateDigit(hours, i);
List<Integer> l2 = generateDigit(mins, num - i);
for (int i1 : l1) {
if (i1 >= 12) continue;
for (int i2 : l2) {
if (i2 >= 60) continue;
res.add(i1 + ":" + (i2 < 10 ? "0" + i2 : i2));
}
}
}
return res;
}
public List<Integer> generateDigit(int[] nums, int count) {
List<Integer> res = new ArrayList<>();
helper(nums, count, 0, 0, res);
return res;
}
//count = 还剩几个点点;pos = 点点在可能的数字的第几位;sum = 所有点点加起来的数字,即时针/分针数字
public void helper(int[] nums, int count, int pos, int sum, List<Integer> res) {
if (count == 0) {
res.add(sum);
return;
}
for (int i = pos; i < nums.length; i++) {
helper(nums, count - 1, i + 1, sum + nums[i], res);
}
}
}
Last updated