剑指Offer——矩形覆盖

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;
    }
};
posted @ 2017-06-30 23:34  清水汪汪  阅读(126)  评论(0编辑  收藏  举报