关于LeetCode中Binary Watch一题的理解

来源:互联网 发布:淘宝搭配套餐 编辑:程序博客网 时间:2024/05/22 05:04

题目如下:

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 = 1Return: ["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".
    遍历各种可能性什么的最麻烦了,我使用的方法是直接把把60种可能性列出来,然后在进行小时和分钟的匹配,这样就是一个双重循环的问题了,十分方便。当然了,缺点就是在手写这60种情况的时候真是萌萌哒,还写错了好几次......好了,直接上已Accepted的代码,由于是用空间换时间,所以速度什么的非常快。

    public List<String> readBinaryWatch(int num) {        int hour[][] = {{0},{1,2,4,8},{3,5,6,9,10},{7,11}};        int minutes[][] = {{0},{1,2,4,8,16,32},{3,5,6,9,10,12,17,18,20,24,33,34,36,40,48},            {7,11,13,14,19,21,22,25,26,28,35,37,38,41,42,44,49,50,52,56},            {15,54,23,27,29,30,39,51,43,45,46,57,58,53},{31,47,55,59}        };        List<String> result = new LinkedList<String>();        int boundary = num>=4?4:num+1;        for(int i=0;i<boundary;i++){            int index = num-i;            if(index>5) continue;            for(int j=0;j<hour[i].length;j++){                for(int k=0;k<minutes[index].length;k++){                    String minute;                    if(minutes[index][k]/10==0){                        minute = "0"+minutes[index][k];                    }else{                        minute = ""+minutes[index][k];                    }                    String temp = hour[i][j]+":"+minute;                    result.add(temp);                }            }        }        return result;    }
    评论区里这个方法好屌,让我感觉自己宛如一个智障,代码如下:

    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;            }
    好在这个评论区的方法有一个缺点,就是速度比较慢......要不然真是碾压啊。

    评论区中还有一种使用backtracking的方法,地址在这里:https://discuss.leetcode.com/topic/59494/3ms-java-solution-using-backtracking-and-idea-of-permutation-and-combination。感兴趣的可以自己看一下...

0 0