zoukankan      html  css  js  c++  java
  • C#学习笔记之——矩形覆盖问题

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

    首先我们来画个图

    1

    只有一种情况

    2

    有两种情况

    3

    有三种情况

    4,以此类推,2*4的矩形有5种

    5    2*5的矩形有8种,可以发现这个是类似斐波那契数列的形式

    不使用递归

    public int rectCover(int number)
    {
        // write code here
        int sum = 0;
        int a = 1, b = 2;
        if (number <= 0)
            sum = 0;
        else if (number == 1)
            sum = 1;
        else if (number == 2)
            sum = 2;
        else
            for (int i = 3; i <= number; i++)
            {
                sum = a + b;
                a = b;
                b = sum;
            }
        return sum;
    }

    使用递归

    public int RectCover(int target) {
        if (target < 1)
            return 0;
        else if (target == 1 || target == 2)
            return target;
        else
            return RectCover(target-1) + RectCover(target-2);
    
    }
  • 相关阅读:
    Python_soket
    Python_正则表达式语法
    Python_math模块
    Python_random模块
    Python_os模块
    Python_time模块
    Java技能树-图片版
    读书笔记---《编写可读代码的艺术》
    Java代码优化建议
    Git常用命令
  • 原文地址:https://www.cnblogs.com/AlinaL/p/12852149.html
Copyright © 2011-2022 走看看