First we can ignore first level of blocks. Let dps,b be the number of ways to put b blocks on s stacks(some stacks could be empty).
Now let’s consider transition, there are three cases:
The first level is full
The leftmost stack is empty
The rightmost stack is empty
For the first case we can simply ignore the first level and the number of ways
is dps,b−s. For the second and the third case, we can ignore the empty
stack and the answer is 2⋅dps−1,b. However, the two cases overlap,
since the scenario where both the leftmost and the rightmost stacks are empty
can be reached from both cases. So we need to subtract dps−2,b. Overall,
the formula is:
dps,b=dps,b−s+2⋅dps−1,b+dps−2,b
This can be calculated recursively with memoization.