Python solution beating 99.86% when I submitted


  • 0
    L

    The major approach to this problem is to consider how many lights are on for hours and how many are for minutes.

    The max number of lights for hours is min(num, 3), because hour <= 11.
    The min number of lights for hours is max(0, num-5) because minutes <= 59, so only 5 lights for minutes at most.

    Then we need a function to return all possible numbers for binary numbers with n digits where m of them are ones.

            def possibleNums(n, m):
                '''Return all possible nums of n digits with m equal to one'''
                if m == n:
                    return [pow(2, n)-1]
                if m == 0:
                    return [0]
                zero = possibleNums(n-1, m)
                one = possibleNums(n-1, m-1)
                one = [z + pow(2, n-1) for z in one]
                return zero + one
    

    Then our main program will construct every possible hour and minute combination and output to answer:

            min_hour = max(0, num-5)
            max_hour = min(3, num)
            
            for i in range(min_hour, max_hour+1):
                hours = possibleNums(4, i)
                hours = [h for h in hours if h <= 11]
                minutes = possibleNums(6, num-i)
                minutes = [m for m in minutes if m <= 59]
                for h in hours:
                    for m in minutes:
                        if m < 10:
                            m = '0' + str(m)
                        else:
                            m = str(m)
                        ans.append(str(h)+':'+m)
               # print hours, minutes
            return ans
    

    My first time sharing solution, hope it helps!


Log in to reply
 

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