Problem statement

https://leetcode.com/problems/domino-and-tromino-tiling/

Solution

As any problem with tiling, here we need to write down recurrent equations. Let Fn be number of tilings for (n+1)×2 board and Gn be number of tilings for (n+1)×2 board with one cell added. Then it can be shown that Fn=Fn1+Fn2+2Gn2 and Gn=Gn1+Fn1 and F0=1,F1=2,G0=1,G1=2.

Complexity

Time and space complexity will be O(n).

Code

class Solution:
    def numTilings(self, N):
        M = 10**9 + 7
        if N <= 2: return N
        F = [1, 2] + [0]*(N-2)
        G = [1, 2] + [0]*(N-2)
        for i in range(2, N):
            F[i] = (F[i-1] + F[i-2] + 2*G[i-2]) % M
            G[i] = (G[i-1] + F[i-1]) % M
            
        return F[-1]

Remark

Moreover it can be shown, that Fn=2Fn1+Fn3, so it can be written using only O(1) memory. Also, as for any recurrent equation, it can be solved in O(log n) * Q^3, if we evaluate power of the transition matrix A = [[2, 0, 1], [1, 0, 0], [0, 1, 0]], where Q = 3 is size of this matrix. We need to evaluate b * A^n, where b = [0, 1, 1] are starting positions.