码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 790. Domino and Tromino Tiling

时间:2019-09-16 11:43:48      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:ble   bsp   for   The   exit   space   amp   HERE   read   

原题链接在这里:https://leetcode.com/problems/domino-and-tromino-tiling/

题目:

We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated.

XX  <- domino

XX  <- "L" tromino
X

Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7.

(In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.)

Example:
Input: 3
Output: 5
Explanation: 
The five different ways are listed below, different letters indicates different tiles:
XYZ XXZ XYY XXY XYY
XYZ YYZ XZZ XYY XXY

Note:

  • N  will be in range [1, 1000].

题解:

Draw some simple examples and find routine.

Let dp[i] denotes ways to tile a 2*i board. 

技术图片

 

 Use int variable instread of array to save space.

Time Complexity: O(N).

Space: O(1).

AC Java:

 1 class Solution {
 2     int M = 1000000007;
 3     public int numTilings(int N) {
 4         if(N <= 0){
 5             return 0;
 6         }
 7         
 8         if(N == 1){
 9             return 1;
10         }
11         
12         if(N == 2){
13             return 2;
14         }
15         
16         if(N == 3){
17             return 5;
18         }
19         
20         int w1 = 1;
21         int w2 = 2;
22         int w3 = 5;
23         for(int i = 4; i<=N; i++){
24             int w4 = (w3*2%M + w1)%M;
25             w1 = w2;
26             w2 = w3;
27             w3 = w4;
28         }
29         
30         return w3;
31     }
32 }

类似Climbing Stairs.

LeetCode 790. Domino and Tromino Tiling

标签:ble   bsp   for   The   exit   space   amp   HERE   read   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11526332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!