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:
1 2
| 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”.
方法1:回溯法
这是一个典型的回溯法的题目,其实就是在10个位置中选n个,前6位组成Minute,后4位组成Hour.
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public List<String> readBinaryWatch(int num) { List<String> ans = new ArrayList<>(); backtracking(num, 0, 0, 0, ans); return ans; } private void backtracking(int num, int start, int res, int count, List<String> ans) { if (count == num) { String str = generateTime(res); if (str != null) ans.add(str); return; } for (int i = start; i < 10; i++) { res |= 1 << i; count++; backtracking(num, i + 1, res, count, ans); int mask = 1 << i; mask = ~mask; res &= mask; count--; } } private String generateTime(int res) { int minute = res & 0x3f; int hour = res >> 6; if (hour >= 12 || minute >= 60) return null; return hour + ":" + (minute >= 10 ? minute : "0" + minute); }
|
方法2:排除法
Ref: https://discuss.leetcode.com/topic/59374/simple-python-java
找到所有Hour和Minute的组合,检查bit count是不是等于num,如果相等,就是所要的结果
1 2 3 4 5 6 7 8
| public List<String> readBinaryWatch(int num) { List<String> times = new ArrayList<>(); for (int h = 0; h < 12; h++) for (int m = 0; m < 60; m++) if (Integer.bitCount(h * 64 + m) == num) times.add(String.format("%d:%02d", h, m)); return times; }
|
这种做法写起来简单,但是时间复杂度不如第一种好,而且这个题目的考点应该就是回溯法,用第二种方法应该不能过关。
另外:
h + ":" + (m >= 10 ? m : "0" + m)
比 String.format("%d:%02d", h, m)
快上不少。