Ad platform~25 min2s · 256 MBtarget O(number of plans × k) with pruning time, O(k) spaceclassic twin: lc-39backtracking
An ad platform sells placements in price tiers, and a tier can be bought many times. An advertiser wants exactly k placements, and wants to spend exactly the campaign budget.
Two plans are the same when they buy each tier the same number of times, whatever the order. The advertiser wants to know how many different plans exist.
Write count_placement_plans(prices, picks, budget).
prices lists the price of each tier. All prices are different, and a tier can be bought any number of times.picks placements in total, and its prices add up to exactly budget.Input: prices = [2,3,5], picks = 4, budget = 14
Output: 2The solution builds a plan from the cheapest tier up, so the same plan is never built in two orders. A tier can be used again, and the search stops when the picks left cannot reach the money left.
| First placement | Money left | Plans that follow |
|---|---|---|
| 2 | 12 | 1, namely 2+2+5+5 |
| 3 | 11 | 1, namely 3+3+3+5 |
| 5 | 9 | 0, because 3 more picks of at least 5 cost 15, which is more than 9 |
The answer is 2.
Input: prices = [2,3,5], picks = 4, budget = 13
Output: 1Only 2+3+3+5 uses four placements and adds up to 13. The plan 3+5+5 also adds up to 13, but it has three placements.
Input: prices = [2,3,5], picks = 3, budget = 50
Output: 0Three placements cost at most 15, so a budget of 50 can never be spent exactly. The search stops at once.
1 ≤ len(prices) ≤ 15, and every price is between 1 and 1,000, with all prices different1 ≤ picks ≤ 14 and 1 ≤ budget ≤ 100,000Choosing 14 placements from 15 tiers, with reuse and no order, gives 40,116,600 different choices. Checking all of them costs about 14 steps each. The search stops when the remaining picks cannot reach the budget, and it visits mostly the plans that work.