问题描述
我遇到了一个问题,我必须填充一个有 2 行和 n 列的矩形。有两个瓷砖,一个是 1*2 瓷砖,第二个是 L 形瓷砖,大边尺寸为 2 个单位,较小边尺寸为 1 个单位。
我通过动态编程解决了这个问题,但不太确定它是否正常工作。如果不是,这个问题的正确自下而上代码是什么。 以下是我的解决方案的功能片段。
对于重复,可以以一种方式填充一列,垂直放置第一个瓦片,可以通过将第一种类型的瓦片一个接一个地水平放置来以一种方式填充两个相邻的列。相邻的三列可以通过将两个L形以2种方式倒置对齐,相邻的四个列可以由两个彼此相对的L形瓷砖和水平放置的第一种瓷砖以2种方式填充。>
int tileways(int n) //n=no.of columns of the rectangle.
{
int i;
int a[n+4];
a[0]=0;
a[1]=0;
a[2]=0;
a[3]=1;
for(i=4;i<n+4;i++)
{
a[i]=a[i-1]+a[i-2]+2*a[i-3]+2*a[i-4];
}
return a[n+3];
}
解决方法
使用我第一条评论中的方法。
l[3]
配置:
L[3]
配置:
#include <iostream>
using namespace std;
int tileways(int n) //n=no.of columns of the rectangle.
{
int l[20];//straight border
int L[20];//extra square
l[0] = 1;
l[1] = 1;
L[0] = 0;
L[1] = 1;
for (int i = 2; i <=n; i++) {
l[i] = l[i-1] + l[i-2] + 2*L[i-2];
//add | to the last straight,= to the 2nd last straight,//two cases of L to extra
L[i] = l[i-1] + L[i-1];
//add L to the last straight,- to the extra
}
return l[n];
}
int main() {
for (int i = 1; i < 10; i++)
std::cout<<i<<" "<< tileways(i)<<std::endl;
return 0;
}
ideone 结果
1 1
2 2
3 5
4 11
5 24
6 53
7 117
8 258
9 569
供参考:OEIS sequence number of possible tilings of a 2 X n board,using dominos and L-shaped trominos.
1,2,5,11,24,53,117,258