Two-dimensional Dynamic Programming
139 / 170Two-dimensional Dynamic ProgrammingLesson 4 of 11About 47 min
The subtlest thing in either DP unit. Two nested loops, swapped, count two different things.
The two versions differ only in which loop is outer. Nothing else changes, and the answers are not close.
Here is the natural loop, which counts arrangements, with the same question listed out by hand underneath so the gap is visible.
def count_arrangements(target, sizes): ways = [0] * (target + 1) ways[0] = 1 for amount in range(1, target + 1): # amounts outside for size in sizes: if size <= amount: ways[amount] += ways[amount - size] return ways[target] print("counted:", count_arrangements(4, [1, 2]))print("listed: ", ["1+1+1+1", "1+1+2", "1+2+1", "2+1+1", "2+2"])print("as multisets, ignoring order:", ["1+1+1+1", "1+1+2", "2+2"])Both versions have the same two loops, the same table, and the same update. Only the nesting differs. Which nesting counts each multiset once, so that 1 then 2 and 2 then 1 are not counted separately?
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.