为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode790. 多米诺和托米诺平铺 | Domino and Tromino Tiling

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10545719.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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].

有两种形状的瓷砖:一种是 2x1 的多米诺形,另一种是形如 "L" 的托米诺形。两种形状都可以旋转。

XX  <- 多米诺

XX  <- "L" 托米诺
X

给定 N 的值,有多少种方法可以平铺 2 x N 的面板?返回值 mod 10^9 + 7。

(平铺指的是每个正方形都必须有瓷砖覆盖。两个平铺不同,当且仅当面板上有四个方向上的相邻单元中的两个,使得恰好有一个平铺有一个瓷砖占据两个正方形。)

示例:
输入: 3
输出: 5
解释: 
下面列出了五种不同的方法,不同字母代表不同瓷砖:
XYZ XXZ XYY XXY XYY
XYZ YYZ XZZ XYY XXY

提示:

  • N  的范围是 [1, 1000]

Runtime: 4 ms
Memory Usage: 19 MB
 1 class Solution {
 2     func numTilings(_ N: Int) -> Int {
 3         switch N
 4         {
 5             case 0:
 6             return 1
 7             case 1,2:
 8             return N
 9             default:
10             break
11         }        
12         var M:Int = Int(1e9) + 7
13         var dp:[Int] = [Int](repeating:0,count:N + 1)
14         dp[0] = 1
15         dp[1] = 1
16         dp[2] = 2
17         for i in 3...N
18         {
19             dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % M
20         }      
21         return dp[N]
22     }
23 }

4ms

 1 class Solution {
 2     func numTilings(_ N: Int) -> Int {
 3         let MOD = 1000000007
 4         if N == 1 { return 1 }
 5         if N == 2 { return 2 }
 6         var dp = [Int](repeating: 0, count: N+1)
 7         dp[0] = 1; dp[1] = 1; dp[2] = 2
 8         for i in 3...N {
 9             dp[i] = (2*dp[i-1] + dp[i-3])%MOD
10         }
11         return dp[N]
12     }
13 }

 

posted @ 2019-03-17 09:54  为敢技术  阅读(405)  评论(0编辑  收藏  举报