Skip to content

Latest commit

 

History

History
94 lines (47 loc) · 1.98 KB

0401._binary_watch.md

File metadata and controls

94 lines (47 loc) · 1.98 KB

401. Binary Watch

难度: Easy

刷题内容

原题连接

内容描述

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 = 1
Return: ["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".

解题方案

思路 1 - 时间复杂度: O(10! / num! / (10-num)!)- 空间复杂度: O(1)******

注意到题目中用的是12小时制

用leads代表各个灯,一共10个,前4个是hour的灯,后6个是minute的灯

idx代表处理到第几个灯了,lights_num代表目前已经亮了几个灯了

beats 74.27%

class Solution(object):
    def readBinaryWatch(self, num):
        """
        :type num: int
        :rtype: List[str]
        """
        res = []
        
        def backtracking(leds, idx, lights_num): 
            if lights_num == num:
                hour, minute = int(''.join(leds[:4]), 2), int(''.join(leds[4:]), 2)
                if hour < 12 and minute < 60:
                    res.append('{}:{:02d}'.format(hour, minute))
                return
            for j in range(idx, 10):
                leds[j] = '1'
                backtracking(leds[:], j+1, lights_num+1)
                leds[j] = '0'
                
        backtracking(['0'] * 10, 0, 0)
        return res