Python solution


  • 0
    N

    Simple enumeration of all possible combination of 1 bits.

        def readBinaryWatch(self, num):
            def getTimeStr(h, m):
                h, m = str(h), str(m) if m >= 10 else "0" + str(m)
                return h + ":" + m
                
            def genPerm(remaining, h, m, index):
                if remaining == 0:
                    if h < 12 and m < 60:
                        yield getTimeStr(h, m)
                else:
                    for i in range(index, 10-remaining+1):
                        newh, newm = h, m
                        if i <= 5:
                            newm += 1 << i
                        else:
                            newh += 1 << (i - 6)
                        for p in genPerm(remaining-1, newh, newm, i+1):
                            yield p
            return list(getPerm(num, 0, 0, 0))
    

Log in to reply
 

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