当前位置:  首页>> 技术小册>> 数据结构与算法(下)

题目描述

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

解法

覆盖 2*n 的矩形:

  • 可以先覆盖 2*n-1 的矩形,再覆盖一个 2*1 的矩形;
  • 也可以先覆盖 2*(n-2) 的矩形,再覆盖两个 1*2 的矩形。

解法一:利用数组存放结果

  1. /**
  2. * @author bingo
  3. * @since 2018/11/23
  4. */
  5. public class Solution {
  6. /**
  7. * 矩形覆盖
  8. * @param target 2*target大小的矩形
  9. * @return 多少种覆盖方法
  10. */
  11. public int RectCover(int target) {
  12. if (target < 3) {
  13. return target;
  14. }
  15. int[] res = new int[target + 1];
  16. res[1] = 1;
  17. res[2] = 2;
  18. for (int i = 3; i <= target; ++i) {
  19. res[i] = res[i - 1] + res[i - 2];
  20. }
  21. return res[target];
  22. }
  23. }

解法二:直接用变量存储结果

  1. /**
  2. * @author bingo
  3. * @since 2018/11/23
  4. */
  5. public class Solution {
  6. /**
  7. * 矩形覆盖
  8. * @param target 2*target大小的矩形
  9. * @return 多少种覆盖方法
  10. */
  11. public int RectCover(int target) {
  12. if (target < 3) {
  13. return target;
  14. }
  15. int res1 = 1;
  16. int res2 = 2;
  17. int res = 0;
  18. for (int i = 3; i <= target; ++i) {
  19. res = res1 + res2;
  20. res1 = res2;
  21. res2 = res;
  22. }
  23. return res;
  24. }
  25. }

测试用例

  1. 功能测试(如输入 3、5、10 等);
  2. 边界值测试(如输入 0、1、2);
  3. 性能测试(输入较大的数字,如 40、50、100 等)。

该分类下的相关小册推荐: