Question
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.
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
the above binary watch reads “3:25”.
一个二进制表有两排灯,上面一排的4盏代表0-11小时,下面一排的6盏代表0-59分钟。每个LED灯。每个LED灯的表现形式为1或0,最右侧代表最低位。现在给出一个非负整数n,它代表当前亮着的LED灯的个数,返回所有可能的表的时间。
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”]
Solution
回溯解。我们只需要遍历n盏亮着的灯的所有组合,并且将小时 H < 12 且 分钟 M < 60 的组合保存下来即可。
public class Solution { public List<String> readBinaryWatch(int num) { List<String> res = new ArrayList<>(); backtracking(0, num, new boolean[10], res); return res; } /** * 思路:利用回溯遍历所有组合,只取小于H < 12小时且M < 59分钟的组合添加到res返回 * @param start:从第以start为索引的灯开始亮 * @param num:还需要亮的灯数 * @param choose:表示10盏灯的亮暗情况(true代表亮,false代表暗) * @param res:返回列表结果 */ public void backtracking(int start, int num, boolean[] choose, List<String> res){ // 10盏灯的代表数值(前4个代表小时,后6个代表分钟) int[] selectable = new int[]{1, 2, 4, 8, 1, 2, 4, 8, 16, 32}; int hh = 0, mm = 0; // 如果已经点亮完所需的盏数,那么统计当前的H和M if(num == 0){ for(int i = 0; i < 10; i++){ if(choose[i]){ if(i < 4) hh += selectable[i]; else mm += selectable[i]; } } // 只取 H < 12 且 M < 60 的组合 if(hh < 12 && mm < 60){ if(mm < 10) res.add(hh + ":0" + mm); else res.add(hh + ":" + mm); } } // 每次从start:10中选择一盏灯点亮 for(int i = start; i < 10; i++){ choose[i] = true; backtracking(i + 1, num - 1, choose, res); choose[i] = false; } } }