Simple, Easy, Python DFS solution


  • 1
    J
    Use Helper arrays to help us to represent binary numbers.
    hours * 100 to distinguish that from minutes.
    then just easy and normal dfs to retrieve all combinations. 
    
    
    def readBinaryWatch(self, num):
        """
        :type num: int
        :rtype: List[str]
        """
        nums = [1,2,4,8,16,32,100,200,400,800]
        res = []
        self.dfs(nums, 0, 0, num, 0, res)
        return res
    
    def dfs(self, nums, level, idx, num, path, res):
        if level == num:
            hours = path/100
            minutes = path%100
            if hours > 11 or minutes > 59:
                return
            elif minutes < 10:
                res.append(str(hours)+":"+"0"+str(minutes))
                return
            else:
                res.append(str(hours)+":"+str(minutes))
                return
            
        for i in range(idx, len(nums)):
            self.dfs(nums, level+1, i+1, num, path+nums[i], res)

Log in to reply
 

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