subsets : zero left padding : leetcode 78

leetcode 78

求解序列的所有子集。
例如: [1, 2, 3].
所有子集爲:[ [ ], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3] ]

其中一種解題思路爲:
使用2進制來表示,組合中是否包含某個元素。
例如 001–> [3], 101–>[1, 3], 111–>[1, 2, 3]
因此只有列出 [0, 2n) 的2進製表示,就可以求出所有的子集。

求解2進製表示時,有一個“zero left padding” 的問題。
例如 1 的二進制表示爲 0b1, 但是我們需要獲得:0b001
具體解決方法見下面代碼。在這裏也學習了bin()函數的用法。

    def subsets_leetcode2(nums: List[int]) -> List[List[int]]:
        n = len(nums)
        nth_bit = 1 << n
        output = []
        for i in range(0, 2**n):
            # generate bitmask from 0..00 to 1..11
            # bin() will return the string of binary number.
            # in order to deal with "zero left padding", we need to add 'nth_bit'.
            # for example: when n = 3, bin(1) = '0b1', but we need to get '0b001'.
            # Therefore, we use nth_bit(1<<3 = 8), bin(1|8) = '0b1001', so bin(1|4)[3:] = '001'
            bitmask = bin(i | nth_bit)[3:]
            combination = [nums[j] for j in range(n) if bitmask[j] == '1']
            output.append(combination)
        return output

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