📜  多米诺骨牌平铺

📅  最后修改于: 2021-09-22 10:09:03             🧑  作者: Mango

给定一个3 xn 的板,找出用2 x 1多米诺骨牌填充它的方法数。

示例 1
以下是填充3 x 2板的所有3 种可能方法。

示例 2
这是填充 3 x 8 板的一种可能方法。你必须找到所有可能的方法来做到这一点。

例子 :

Input : 2
Output : 3

Input : 8
Output : 153

Input : 12
Output : 2131

定义子问题:
在填充板的任何时候,最后一列可能处于三种可能的状态:

An =  No. of ways to completely fill a 3 x n board. (We need to find this)
Bn =  No. of ways to fill a 3 x n board with top corner in last column not filled.
Cn =  No. of ways to fill a 3 x n board with bottom corner in last column not filled.

注意:以下状态是不可能达到的:

寻找复发
注意:即使BnCn是不同的状态,它们对于相同的‘n’也是相等Bn = Cn
因此,我们只需要计算其中之一。

计算一个:

 A_{n} = A_{n-2} + B_{n-1} + C_{n-1}
 A_{n} = A_{n-2} + 2*(B_{n-1})

计算 Bn:

 B_{n} = A_{n-1} + B_{n-2}

最终递归关系是:

 A_{n} = A_{n-2} + 2*(B_{n-1})  B_{n} = A_{n-1} + B_{n-2}

基本案例:

 A_0 = 1 \hspace{0.5cm}, \hspace{0.5cm} A_1 = 0  B_0 = 0 \hspace{0.5cm}, \hspace{0.5cm} B_1 = 1

C++
// C++ program to find no. of ways
// to fill a 3xn board with 2x1 dominoes.
#include 
using namespace std;
  
int countWays(int n)
{
    int A[n + 1], B[n + 1];
    A[0] = 1, A[1] = 0, B[0] = 0, B[1] = 1;
    for (int i = 2; i <= n; i++) {
        A[i] = A[i - 2] + 2 * B[i - 1];
        B[i] = A[i - 1] + B[i - 2];
    }
  
    return A[n];
}
  
int main()
{
    int n = 8;
    cout << countWays(n);
    return 0;
}


Java
// Java program to find no. of ways
// to fill a 3xn board with 2x1 dominoes.
import java.io.*;
  
class GFG {
  
    static int countWays(int n)
    {
        int []A = new int[n+1];
        int []B = new int[n+1];
        A[0] = 1; A[1] = 0;
        B[0] = 0; B[1] = 1;
        for (int i = 2; i <= n; i++) 
        {
            A[i] = A[i - 2] + 2 * B[i - 1];
            B[i] = A[i - 1] + B[i - 2];
        }
      
        return A[n];
    }
  
    // Driver code
    public static void main (String[] args) 
    {
        int n = 8;
        System.out.println(countWays(n));
    }
}
  
// This code is contributed by anuj_67.


Python 3
# Python 3 program to find no. of ways
# to fill a 3xn board with 2x1 dominoes.
  
def countWays(n):
  
    A = [0] * (n + 1)
    B = [0] * (n + 1)
    A[0] = 1
    A[1] = 0
    B[0] = 0
    B[1] = 1
    for i in range(2, n+1):
        A[i] = A[i - 2] + 2 * B[i - 1]
        B[i] = A[i - 1] + B[i - 2]
      
    return A[n]
  
n = 8
print(countWays(n))
  
# This code is contributed by Smitha


C#
// C# program to find no. of ways
// to fill a 3xn board with 2x1 dominoes.
using System;
  
class GFG {
  
    static int countWays(int n)
    {
        int []A = new int[n+1];
        int []B = new int[n+1];
        A[0] = 1; A[1] = 0;
        B[0] = 0; B[1] = 1;
        for (int i = 2; i <= n; i++) 
        {
            A[i] = A[i - 2] + 2 * B[i - 1];
            B[i] = A[i - 1] + B[i - 2];
        }
      
        return A[n];
    }
  
    // Driver code
    public static void Main () 
    {
        int n = 8;
        Console.WriteLine(countWays(n));
    }
}
  
// This code is contributed by anuj_67.


PHP


输出 :
153