Skip to content
advent of code 2015

day 17

no such thing as too much

approach

the containers are sorted and a memoized recursion over (index, litres left) either uses the current container or skips it, counting the ways to reach exactly zero.

part 2 does it in two passes with the same shape: dp1 finds the minimum number of containers that can hold the target, and dp2 adds that count as a third dimension to count only the combinations that use exactly that many.

the trick

find the minimum container count first, then count again with that count as an extra dimension.

python
def part1(liters, containers):
    @lru_cache(None)
    def dp(i, s):
        if i == len(containers):
            return int(s == 0)
        if s < 0:
            return 0
        if s == 0:
            return 1
        w  = dp(i + 1, s - containers[i])
        wo = dp(i + 1, s)
        return w + wo
    return dp(0, liters)