#40
Combination Sum II
medium· Backtrackingruns: 0Given a collection of candidate numbers candidates and a target target, find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may be used only once in each combination. The solution must not contain duplicate combinations.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 737
class Solution:
def combinationSum2(
self, candidates: list[int], target: int
) -> list[list[int]]:
candidates.sort()
result = []
path = []
def backtrack(start: int, remaining: int) -> None:
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
if i > start and candidates[i] == candidates[i - 1]:
continue
if candidates[i] > remaining:
break
path.append(candidates[i])
backtrack(i + 1, remaining - candidates[i])
path.pop()
backtrack(0, target)
return result
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.