Created
May 15, 2020 11:12
-
-
Save coldmanck/89614fd33b0d4d0acc608a623d496cd6 to your computer and use it in GitHub Desktop.
LeetCode 0063 combination sum (BFS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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