《剑指offer》——矩形覆盖

来源:互联网 发布:js arguments递归 编辑:程序博客网 时间:2024/06/06 02:08

T:

题目描述
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

这个题目乍看不知道怎么入手,如果稍加分析的话,会发现其实很简单。

分析如下图:
这里写图片描述

可得到递推公式:d(n) = d(n-1) + d(n-2)

code:

    package niuke.sward2offer.matrixCover;    /**     * T: 举行覆盖     *      * 题目描述     * 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。     * 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?     *      * date: 2015.11.6 19:56     * @author SSS     *     */    public class Solution {        /**         * 其实就是一个斐波那契数列,满足公式:d(n) = d(n-1) + d(n-2)          * @param target         * @return         */        public int RectCover(int target) {            int tempNum = 1;            int result = 2;            if (target == 0) {                return 1;            }            if (target == 1 || target == 2) {                return target;            }            int count = 2;            while (count < target) {                result += tempNum;                tempNum = result - tempNum;                count ++;            }            return result;        }        public static void main(String []args) {            Solution solution = new Solution();            int target = 5;            System.out.println(solution.RectCover(target));        }    }
0 0
原创粉丝点击