Legal string [Dynamic Planning], string Dynamic Planning
A string may consist of only letters A, B, and C. If any of the three adjacent letters is the same, it is invalid. Evaluate the number of valid strings whose length is n? For example, ABBBCA is invalid and ACCBCCA is legal.
The idea of Dynamic Planning-do you really want to enumerate?
Dp [I] [0]: Number of valid strings with the length of I and the last two
Dp [I] [1]: Number of valid strings with the same length as I and the last two
Recurrence: dp [I] [0] = (dp [I-1] [0] * 2 + dp [I-1] [1] * 2)
Dp [I] [1] = dp [I-1] [0]
Initial Value
Dp [1] [0] = 3, dp [1] [1] = 0
Result
Dp [n] [0] + dp [n] [1]
Space Optimization
Dp [I] [0, 1] is only related to dp [I-1] [0, 1] and can save High Dimensional
Time Complexity
O (n)
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.