How to calculate how many steps are needed to solve the Nine Links

According to the gameplay of Nine Links, we can know that facing a state where all the rings are in the "down ring", if we want to go forward nnn ring, then we must first go up firstn − 1 n-1n1 ring, then down beforen − 2 n-2n2nd ring, then go up tonnn ring, then go forwardn − 2 n-2n2 rings. Therefore, if we put theupper nnThe number of steps required for the n loop is recorded asan a_nan, Then the sequence an a_nanSatisfy:

a n = a n − 1 + 2 a n − 2 + 1 (1) a_n=a_{n-1}+2a_{n-2}+1\tag{1} an=an1+2 an2+1(1)

Here we think we can only operate one ring at a time, that is, we cannot move up and down the first two rings at the same time

Using this recurrence formula to write a python program, you can easily calculate an = 341 a_n=341an=341

def func(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        return func(n-1) + 2*func(n-2)+1
res = func(9)
print(res)

So how to get an a_nanThe general term formula of, after consulting the data extensively, we learned that an a_nanIt belongs to the second-order linear constant coefficient non-homogeneous recurrence relationship. It can be calculated by formula.

The specific calculation method can be jumped to the reference materials at the end of the article

The final calculation result is
an = − 1 6 (− 1) n + 2 3 2 n − 1 2 a_n=-\frac{1}{6}(-1)^n+\frac{2}{3}2^n -\frac{1}{2}an=61(1)n+322n21

Also get a 9 = 341 a_9=341a9=3 4 1 Consistent with python calculation results.


Reference materials:

Baidu Library-2.4 Linear Constant Coefficient Inhomogeneous Recurrence Relation

CSDN-python implementation of Fibonacci sequence

Guess you like

Origin blog.csdn.net/Infinity_07/article/details/113439091