GATE Computer ScienceVery hardGATE CS (PYQ pattern)

In how many ways can 12 be written as an ordered sum of parts from {1, 2, 3} such that no two adjacent parts are equal (e.g. 1+2+1+3+… is allowed, 2+2+… is not)?

  1. A. 58
  2. B. 927
  3. C. 64
  4. D. 49

Correct answer: A. 58

Use a DP f(r, last) = number of ways to finish a remaining total r when the previous part was last: f(0, ·) = 1, f(r, last) = Σ f(r − p, p) over p ∈ {1, 2, 3}, p ≠ last, p ≤ r. Evaluating gives f(12, none) = 58. Without the adjacency rule there are 927 compositions.

More Algorithms questions

Exams that ask this topic