Skip to content

Instantly share code, notes, and snippets.

@coldmanck
Created May 15, 2020 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coldmanck/89614fd33b0d4d0acc608a623d496cd6 to your computer and use it in GitHub Desktop.
Save coldmanck/89614fd33b0d4d0acc608a623d496cd6 to your computer and use it in GitHub Desktop.
LeetCode 0063 combination sum (BFS)
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
# BFS
from collections import deque
queue = deque() # [cur_target, cur_ans, cand_idx]
queue.append((target, [], 0))
ans = []
while queue:
cur_target, cur_ans, cand_idx = queue.popleft()
for i in range(cand_idx, len(candidates)):
new_target = cur_target - candidates[i]
if new_target == 0:
ans.append(cur_ans + [candidates[i]])
elif new_target > 0:
queue.append((cur_target - candidates[i], cur_ans + [candidates[i]], i))
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment