Online store~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-70dp
An online store gives each customer a loyalty tier, from tier 0 up to a top tier. A purchase moves a customer up one tier or two tiers.
Marketing wants to know how many different sequences of purchases take a customer from tier 0 to the top tier. They plan with up to 70 tiers.
Your team lead says: Count the sequences for any number of tiers, and make it instant.
Write ways_to_reach(tiers).
tiers. A move may not go past the top tier.tiers = 1 there is one sequence.Input: tiers = 4
Output: 5The recursion counts the sequences for a tier as the sequences for the tier below it, plus those for the tier two below it. It stores each answer.
| Call | Tier | What happens |
|---|---|---|
| 1 | 4 | not stored, so it asks for tiers 3 and 2 |
| 2 | 3 | not stored, so it asks for tiers 2 and 1 |
| 3 | 2 | not stored, so it asks for tiers 1 and 0 |
| 4 | 1 | base case: 1 way |
| 5 | 0 | base case: 1 way |
| 6 | 1 | base case: 1 way |
| 7 | 2 | stored: 2 ways, returned at once |
Tier 2 stores 2 ways, and tier 3 stores 3 ways. Tier 4 adds tier 3 and tier 2 for 5 ways. The recursion made 7 calls, where the plain one makes 9.
Input: tiers = 1
Output: 1There is one tier to climb, and one move of one tier does it. The answer is 1.
Input: tiers = 10
Output: 89Ten tiers give 89 sequences. They are the number of ways to write 10 as an ordered sum of 1s and 2s.
1 ≤ tiers ≤ 70With 70 tiers there are 308,061,521,170,129 sequences, which is above 2^32 and below 2^53, so use a 64-bit integer. The plain recursion makes 616,123,042,340,257 calls and cannot finish. A cache makes 139 calls.