backtrace&usage of slice notation[:] - leetcode 77. Combinations

    def combine(self, n: int, k: int) -> List[List[int]]:
        """
        Input: n = 4, k = 2
        Output:
        [
          [2,4],
          [3,4],
          [2,3],
          [1,2],
          [1,3],
          [1,4],
        ]
        :param n:
        :param k:
        :return:
        """
        def helper(combine, start, items, k):
            if k == 0:
                output.append(combine[:]) # [:] is slice notation for copy
                return

            for i in range(start, len(items)):
                combine.append(items[i])
                helper(combine, i+1, items, k-1)
                combine.pop()

        output = []
        l = list()
        items = [i for i in range(1, n+1)]
        helper(l, 0, items, k)

        return output

python slice notation:

a = [1,2]
b = a[::-1]
print("b:{}".format(b))
a.insert(1, 3)
print("a:{}".format(a))
c = a[:] # same as copy.deepcopy(a), but better
print("c's id:{} value:{}".format(id(c), c))
print("a's id:{} value:{}".format(id(a), a))

output:

b:[2, 1]
a:[1, 3, 2]
c's id:4364104264 value:[1, 3, 2]
a's id:4364114952 value:[1, 3, 2]

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