LC 77 Backtracking 1

LC 77 Backtracking 1


First part of Backtracking.

LC 242, 383

77 combinations


Brute Force

  • We start with all combinations of size one, then we could just append add one more element till all are of size k.

# LC 383
def combine2(self, n: int, k: int) -> List[List[int]]:
    ret = deque([[i] for i in range(1, n+1)])
    while len(ret[0]) < k:
        lst = ret.popleft()
        for i in range(lst[-1]+1, n+1):
            ret.append(lst + [i])
    return list(ret)

Backtrack

1. cur as List[int]
  • This is what I started with the backtracking algorithm, which is quite hard to think of. However, what could be done is to using cur as the path containing the combination, which helps to records the path in the tree.
def combine3(self, n: int, k: int) -> List[List[int]]:
    def backtrack(n: int, k: int, cur: List[int],result:List[List[int]]) -> None:
        if len(cur) == k:
            result.append(cur[:])
            return
        for i in range(cur[-1]+1, n+1):
            cur.append(i)
            backtrack(n, k, cur, result)
            cur.pop()
    ret = []
    for i in range(1, n+1):
        thread = Thread(target=backtrack, args=(n, k, [i], ret))
        thread.start()
        thread.join()
    return ret
1. cur as index

More details could be found here: 第77题. 组合

def combine4(self, n: int, k: int) -> List[List[int]]:
    path = []
    ret = []
    def backtrack(count: int) -> None:
        if len(path) == k:
            ret.append(path[:])
            return
        for i in range(count, n+1):
            path.append(i)
            backtrack(i+1)
            path.pop()
    path.clear()
    ret.clear()
    backtrack(1)
    return ret

Library method

def combine(self, n: int, k: int) -> List[List[int]]:
    return list(combinations(range(1, n+1), k))

Summary:


  • The template helps a lot to come up with a method of backtracking.
  • Still working on the bst.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值