剑指offer题目10:矩形覆盖
题目描述
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
解答思路
哈哈,依旧是斐波那契数列系列。
画图查看一下n和1的区别。
f(1)
| 1 |
|---|
| 1 |
f(n)
| n | n | n | n | n |
|---|---|---|---|---|
| n | n | n | n | n |
思考得出:
- n为1的时候,有1种填充方式
- n为2的时候,有2种填充方式
- n>2的时候,第一次填充的时候可以用1块直接竖着放,接下来还有n-1块去填充,也可以用2块横着放,接下来还有n-2块去填充。因此得出f(n) = f(n-1) + f(n-2)
用1块竖着填充
| 1 | n | n | n | n |
|---|---|---|---|---|
| 1 | n | n | n | n |
用2块横着填充
| 1 | 1 | n | n | n |
|---|---|---|---|---|
| 2 | 2 | n | n | n |
实现代码
class Solution {
public:
int rectCover(int number) {
int fn = 0;
int fn1 = 2;
int fn2 = 1;
if(number == 0 || number == 1 || number == 2) {
return number;
}
for (int i = 3; i <= number; ++i)
{
fn = fn1 + fn2;
fn2 = fn1;
fn1 = fn;
}
return fn;
}
};
作者:大傻逼
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号