LeetCode 790. Domino and Tromino Tiling

原题链接在这里: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.

posted @ 2019-09-16 11:15  Dylan_Java_NYC  阅读(395)  评论(0编辑  收藏  举报