Dynamic Programming21 sections · 916 units
Open in Course

Consecutive Ones - Walkthrough

Tracing with previous digit

Count binary numbers 101\leq 101 (5 in decimal) with no consecutive 1s. Track the previous digit. N = 101 in binary. Position 00: try 00 (loose) or 1 (tight).

If 11, prevDigit = 1. Position 11: if prev = 1 and tight, can only try 00 (since 1 would make consecutive 1s). If loose, try both but skip 1 if prev = 1. Position 22: continue. Valid numbers: 000000, 001001, 010010, 100, 101. That's 5 numbers. The DP counts all valid paths.