Straight forward Python solution with explanation

  • 0

    This problem equals to 'set num of 10 bits to 1s, and others to 0s'. So I use a helper method getBinaryList(n,num).
    n represents the number of bits, and num is the number of bits we select and set to 1s. Set other bits to 0s.
    Here is the key:
    getBinaryList(n,num) = {1, getBinaryList(n-1,num-1)} + {0, getBinaryList(n-1,num)}

    {1, getBinaryList(n-1,num-1)} means the set that we add 1 before getBinaryList(n-1,num-1)

    class Solution(object):
        def readBinaryWatch(self, num):
            :type num: int
            :rtype: List[str]
            def getBinaryList(n,num):
                if n < 1: return []
                if num>n: return []
                if num==0: return [[0]*n]
                if num==n: return [[1]*n]
                r = []
                for i in getBinaryList(n-1, num):
                    tmp = [0]
                for i in getBinaryList(n-1, num-1):
                    tmp = [1]
                return r
            l = getBinaryList(10, num)
            r = []
            for lst in l:
                h = lst[:4]
                m = lst[4:]
                hour, minute = 0, 0
                for i in h:
                    hour = 2*hour + i
                for i in m:
                    minute = 2*minute + i
                if not (hour >11 or minute>59):
                    r.append("%d:%02d" % (hour, minute))
            return r

Log in to reply

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