Climbing Stairs with Quick Power Calculations

Get into the habit of writing together! This is the 5th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

Topic description

Suppose you are climbing stairs. You need  n steps to get to the top.

You can climb  one 1 or  2 more steps at a time. How many different ways can you get to the top of a building?

image.png

image.png

Thought analysis

There are many algorithms for climbing stairs, from the recursion learned at the beginning, and the constant storage of the pre value through two variables (this idea has a shadow of dynamic programming, which hides a state transition equation, but does not need to apply for additional O( n) level of memory space).

However, recursion requires a deep stack, and the time complexity of dynamic programming is also O(n). Can the time complexity be further reduced?

See the following formula

[ 1 1 1 0 ] [ f ( n ) f ( n 1 ) ] = [ f ( n 1 ) + f ( n ) f ( n ) ] = [ f ( n + 1 ) f ( n ) ] \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} f(n) \\ f(n - 1) \end{bmatrix} = \begin{bmatrix} f(n - 1) + f(n) \\ f(n) \end{bmatrix} = \begin{bmatrix} f(n + 1) \\ f(n) \end{bmatrix}

Therefore

[ 1 1 1 0 ] n [ f ( 1 ) f ( 0 ) ] = [ f ( n + 1 ) f ( n ) ] \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n \begin{bmatrix} f(1) \\ f(0) \end{bmatrix} = \begin{bmatrix} f(n + 1) \\ f(n) \end{bmatrix}

Then the time complexity of this problem simplifies to the solution

[ 1 1 1 0 ] n \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n

time complexity of

To solve this n-th power, we can use the fast power. Change the time complexity of O(n) to O( l o g 2 n log_2n )

Code

 public int[][] pow(int[][] a, int n) {
        int[][] ret = {{1, 0}, {0, 1}};
        while (n > 0) {
            if ((n & 1) == 1) {
                ret = multiply(ret, a);
            }
            n >>= 1;
            a = multiply(a, a);
        }
        return ret;
    }
复制代码

Summarize

In fact, I personally think that it is enough to use dynamic programming for climbing stairs, but occasionally I do encounter some people who pursue time complexity or competitions that require fast power to answer.

The difficulty of fast power is not its implementation, but how to abstract a problem into a problem that can be solved using fast power.

Guess you like

Origin juejin.im/post/7084231510508699685