Leetcode - 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"]
- 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".
=======================SOLUTION=============================
这道题我的第一个想法就是 这个好像和 letter combintion of phone number 那道题目很像,我们可以算出当lights number为k时所有可能的hours再算出相对应 num-k时所有可能minutes, 然后进行组合。 这样的话,我就想着我们应该分步进行。
- 第一步, 算出hours
- 第二步, 算出minutes
- 第三步, 结合hours 和 minutes
- 第四步, 改变 hours lights的个数, 继续上述
当然 我们需要注意的是亮灯个数, 因为hours毕竟一共才4灯,minutes一共才6灯,所以要根据传入的灯总数进行调整。同时, 我们也要注意时针不可以超过11,分针不可以超过59.
代码:
class Solution { int HOUR_LIMIT = 11; int MINUTE_LIMIT = 59; public List<String> readBinaryWatch(int num) { int[] hours = new int[]{1,2,4,8}; int[] minutes = new int[]{1,2,4,8,16,32}; List<String> hoursOptions = new ArrayList<>(); List<String> minutesOptions = new ArrayList<>(); List<String> results = new ArrayList<>(); //separate the formation of hour and minute int options = num > hours.length ? hours.length : num; for (int index = 0; index <= options; index++) { formLightComb(index, hoursOptions, hours, 0, 0, HOUR_LIMIT); int option = minutes.length >= num - index ? num - index : minutes.length; formLightComb(option, minutesOptions, minutes, 0, 0, MINUTE_LIMIT); formTime(minutesOptions, hoursOptions, results, 0, ""); hoursOptions.clear(); minutesOptions.clear(); } return results; } void formLightComb(int num, List<String> results, int[] times, int time, int index, int limit) { if (num == 0) { if (time <= limit) { if (limit == MINUTE_LIMIT && (time / 10 == 0)) { results.add("0" + time); } else { results.add(time + ""); } } return; } for (int i = index; i < times.length; i++) { formLightComb(num - 1, results, times, times[i] + time, i + 1, limit); } } void formTime(List<String> minutes, List<String> ls, List<String> results, int count, String time){ if (count == 2) { results.add(time.substring(1, time.length())); return; } for (int i = 0; i < ls.size(); i++) { formTime(minutes, minutes, results, count + 1, time + ":" + ls.get(i)); } } }