Question
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
Solution
-
递推式子 f(n) = f(n - 1) + f(n - 2)
-
实现有递归和非递归两种
Code
class Solution {
public:
// 递归
int rectCover(int number) {
if (number == 0)
return 0;
if (number == 1)
return 1;
if (number == 2)
return 2;
return rectCover(number - 1) + rectCover(number - 2);
}
// 非递归
int rectCover(int number) {
if (number == 0)
return 0;
if (number == 1)
return 1;
if (number == 2)
return 2;
int sum = 0;
int one = 1;
int two = 2;
for (int i = 3; i <= number; i++) {
sum = one + two;
one = two;
two = sum;
}
return sum;
}
};