Implement combination_sum(candidates, target). Return the unique combinations that sum to target, where each candidate may be reused any number of times.
Explore candidates in index order. Recurse with the same index i so a value can repeat, but never revisit earlier indices. Track remaining = target - chosen; record a copy when it reaches 0 and prune when it drops below 0.
For candidates [2, 3, 6, 7], target 7 the output is [[2, 2, 3], [7]].
def subsets(nums):
res = []
path = []
def bt(start):
res.append(list(path))
for i in range(start, len(nums)):
path.append(nums[i])
bt(i + 1)
path.pop()
bt(0)
return res
def permutations(nums):
res = []
used = [False] * len(nums)
path = []
def bt():
if len(path) == len(nums):
res.append(list(path))
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i])
bt()
path.pop()
used[i] = False
bt()
return res
def combinations(n, k):
res = []
path = []
def bt(start):
if len(path) == k:
res.append(list(path))
return
for i in range(start, n + 1):
path.append(i)
bt(i + 1)
path.pop()
bt(1)
return res
def combination_sum(candidates, target):
"""Return unique combinations summing to target (candidates reusable).
Explore candidates in index order; recurse with the same index i so a
value may repeat, and never revisit earlier indices.
"""
# TODO: track remaining = target - chosen; record a copy when it hits 0,
# prune when it goes below 0.
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Implement combination_sum(candidates, target). Return the unique combinations that sum to target, where each candidate may be reused any number of times.
Explore candidates in index order. Recurse with the same index i so a value can repeat, but never revisit earlier indices. Track remaining = target - chosen; record a copy when it reaches 0 and prune when it drops below 0.
For candidates [2, 3, 6, 7], target 7 the output is [[2, 2, 3], [7]].
Press Run Tests or ββ© to check your solution.