Legal string [Dynamic Planning], string Dynamic Planning

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.