6 line 32ms python solution without exhaustive search


  • 0
    X

    Uses itertools to generate all combinations of i bits for hours and num-i bits for minutes, their Cartesian product gives the result.

    import itertools as it
    
    class Solution(object):
        def readBinaryWatch(self, num):
            res = []
            for i in range(num+1):
                for (h,m) in it.product((sum(x) for x in it.combinations((1<<x for x in range(4)),i)),(sum(x) for x in it.combinations((1<<x for x in range(6)),num-i))):
                    if h<12 and m<60:
                        res.append("{0:d}:{1:02d}".format(h,m))
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.