Ad platform~35 min2s · 256 MBtarget O(partial placements), far fewer than C(n², k) time, O(n) spaceclassic twin: lc-52backtracking
An ad platform lays out banners on a screen of n by n slots. Two banners compete for attention when they share a row, a column, or a diagonal. A layout must never put two banners in such a pair.
The designers want to place exactly k banners. Some rows or columns may stay empty. They ask how many different layouts are valid.
Write count_placements(n, k).
n rows and n columns, and every slot is free.k different slots. Two layouts are different when their sets differ. The order of placing does not matter.0 when there is none.Input: n = 3, k = 2
Output: 8The solution fills the rows from the top, and a row may stay empty. It cuts a branch as soon as a banner would clash. The table counts the layouts by what happens in row 0.
| Row 0 | Layouts that finish below it |
|---|---|
| left empty | 2 |
| banner in column 0 | 2 |
| banner in column 1 | 2 |
| banner in column 2 | 2 |
The total is 2 + 2 + 2 + 2 = 8.
Input: n = 4, k = 4
Output: 2One banner in every row and column with no shared diagonal. The two layouts are mirror images.
Input: n = 3, k = 3
Output: 0Three banners never fit on a three by three grid.
1 ≤ n ≤ 81 ≤ k ≤ 8There are 64 slots, and choosing 5 of them gives 7,624,512 sets. Choosing 8 of them gives 4,426,165,368 sets. Most contain a clash early, so a search that stops at the first clash visits far fewer.