二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)。
    每个 LED 代表一个 0 或 1,最低位在右侧。

    401. 二进制手表 - 图1
    例如,上面的二进制手表读取 “3:25”。
    给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。
    示例:
    输入: n = 1
    返回: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]

    提示:

    • 输出的顺序没有要求。
    • 小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
    • 分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。
    • 超过表示范围(小时 0-11,分钟 0-59)的数据将会被舍弃,也就是说不会出现 “13:00”, “0:61” 等时间。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-watch


    思路:

    1.暴力枚举 2.循环暴力枚举 3.递归 4.bitCount

    1. class Solution {
    2. int []hours ;
    3. int [] mins;
    4. boolean []hourVisited;
    5. boolean []minuteVisited;
    6. int num;
    7. List<String> ans = new ArrayList<>();
    8. public List<String> readBinaryWatch(int num) {
    9. this.num = num;
    10. this.hours = new int []{1,2,4,8};
    11. this.mins = new int []{1,2,4,8,16,32};
    12. this.hourVisited = new boolean[4];
    13. this.minuteVisited = new boolean[6];
    14. for(int i=0;i<=num;i++){
    15. dfs(i,num-i,0,0,0,0);
    16. }
    17. // Collections.sort(ans, new Comparator<String>() {
    18. // @Override
    19. // public int compare(String o1, String o2) {
    20. // String [] s1 = o1.split(":");
    21. // String [] s2 = o2.split(":");
    22. // return Integer.parseInt(s1[0])==Integer.parseInt(s2[0])?Integer.parseInt(s1[1])-Integer.parseInt(s2[1]):Integer.parseInt(s1[0])-Integer.parseInt(s2[0]);
    23. // }
    24. // });
    25. return ans;
    26. }
    27. private void dfs(int num,int count,int hour,int min,int h,int m){
    28. if(num==0&&count==0){
    29. String s = getTime(hour,min);
    30. if(ans.contains(s)) return;
    31. ans.add(s);
    32. return ;
    33. }
    34. if(num>0){
    35. for (int i = h; i < 4; i++) {
    36. if(hourVisited[i]) continue;
    37. if(hour+hours[i]>=12) break;
    38. hourVisited[i] = true;
    39. dfs(num-1,count,hour+hours[i],min,i+1,m);
    40. hourVisited[i] = false;
    41. }
    42. }
    43. if(count>0){
    44. for (int i = m; i < 6; i++) {
    45. if(minuteVisited[i]) continue;
    46. if(min+mins[i]>=60) break;
    47. minuteVisited[i] = true;
    48. dfs(num,count-1,hour,min+mins[i],h,i+1);
    49. minuteVisited[i] = false;
    50. }
    51. }
    52. }
    53. private String getTime(int hour,int min){
    54. StringBuilder ans = new StringBuilder();
    55. ans.append(hour).append(":");
    56. if(min<10){
    57. ans.append(0);
    58. }
    59. ans.append(min);
    60. return ans.toString();
    61. }
    62. }
    1. class Solution{
    2. public List<String>readBinaryWatch(int num){
    3. List<String>times=new ArrayList<>();
    4. for(int h=0;h<12;h++){
    5. for(int m=0;m<60;m++){
    6. if(Integer.bitCount(h)+Integer.bitCount(m)==num)
    7. times.add(String.format("%d:%02d",h,m));
    8. }
    9. }
    10. return times;
    11. }
    12. }