LC 77 Backtracking 1
First part of Backtracking.
LC 242, 383
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.