Backtracking
95 / 170BacktrackingLesson 2 of 10About 42 min
One number in the recursive call decides whether items can repeat and whether orderings count separately.
The same function with only that one argument changed produces genuinely different answers.
def ways_to_total(parts, target, allow_reuse): results, current = [], [] def explore(start, remaining): if remaining == 0: results.append(current[:]) return for index in range(start, len(parts)): if parts[index] > remaining: continue current.append(parts[index]) explore(index if allow_reuse else index + 1, remaining - parts[index]) current.pop() explore(0, target) return results print(ways_to_total([1, 2, 3], 4, True))print(ways_to_total([1, 2, 3], 4, False))You must list every way to make change for an amount using given coin values, where each coin may be used any number of times, and where [1, 3] and [3, 1] count as the same way. What should the recursive call pass?
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.