给定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.
注意:无法达到以下状态:
查找递归
注意:即使Bn和Cn是不同的状态,它们对于相同的‘n’也是相等的。即Bn = Cn
因此,我们只需要计算其中之一即可。
计算一个:
计算Bn:
最终的递归关系为:
基本案例:
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
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。