LeetCode題解(0401):推斷二進制手錶中所有可能的時間(Python)

題目:原題鏈接(簡單)

解法 時間複雜度 空間複雜度 執行用時
Ans 1 (Python) O(total) O(n) 48ms (46.94%)
Ans 2 (Python) O(10^n) O(10^n) 44ms (66.82%)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一(暴力法):

def readBinaryWatch(self, num: int) -> List[str]:
    ans = []
    for h in range(12):
        for m in range(60):
            if bin(h).count("1") + bin(m).count("1") == num:
                ans.append("%d:%02d" % (h, m))
    return ans

解法二(回溯法):

def readBinaryWatch(self, num: int) -> List[str]:
    hour = [1, 2, 4, 8]
    minute = [1, 2, 4, 8, 16, 32]

    ans = []

    def helper(n, index, status):
        if n == 0:
            h = sum([i * j for i, j in zip(hour, status[:4])])
            m = sum([i * j for i, j in zip(minute, status[4:])])
            if h < 12 and m < 60:
                ans.append("%d:%02d" % (h, m))
        else:
            for i in range(index, 10):
                status[i] = 1
                helper(n - 1, i + 1, status)
                status[i] = 0

    helper(num, 0, [0] * 10)

    return ans
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章