微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift]LeetCode351. 安卓解锁模式 $ Android Unlock Patterns

Given an Android 3x3 key lock screen and two integers m and n,where 1 ≤ m ≤ n ≤ 9,count the total number of unlock patterns of the Android lock screen,which consist of minimum of m keys and maximum n keys.

Rules for a valid pattern:

  1. Each pattern must connect at least m keys and at most n keys.
  2. All the keys must be distinct.
  3. If the line connecting two consecutive keys in the pattern passes through any other keys,the other keys must have prevIoUsly selected in the pattern. No jumps through non selected key is allowed.
  4. The order of keys used matters.

分享图片

Explanation:

| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |

Invalid move: 4 - 1 - 3 - 6 
Line 1 - 3 passes through key 2 which had not been selected in the pattern.

Invalid move: 4 - 1 - 9 - 2
Line 1 - 9 passes through key 5 which had not been selected in the pattern.

Valid move: 2 - 4 - 1 - 3 - 6
Line 1 - 3 is valid because it passes through key 2,which had been selected in the pattern

Valid move: 6 - 5 - 4 - 1 - 9 - 2
Line 1 - 9 is valid because it passes through key 5,which had been selected in the pattern.

Example:
Given m = 1, n = 1,return 9.

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

给定一个android 3x3密钥锁屏和两个整数m和n,其中1≤m≤n≤9,计算android锁屏的解锁模式总数,该解锁模式由最小M个密钥和最大N个密钥组成。 

有效模式的规则:

  1.  每个模式必须连接至少M个键和最多N个键。
  2. 所有键必须是不同的。
  3. 如果连接模式中两个连续键的线通过任何其他键,则其他键必须事先在模式中选择。不允许跳过未选定的键。
  4. 钥匙的使用顺序很重要。

分享图片

说明:

| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |

无效移动:4-1-3-6

第1-3行通过模式中未选择的键2。

无效移动:4-1-9-2

第1-9行通过模式中未选择的键5。

有效移动:2-4-1-3-6

第1-3行有效,因为它通过模式中选择的键2

有效移动:6-5-4-1-9-2

第1-9行有效,因为它通过模式中选择的键5。

例子:

给定m=1,n=1,返回9。

信用:

特别感谢@elmirap添加此问题并创建所有测试用例。

Solution:

 1 class Solution {
 2     func numberOfPatterns(_ m:Int,_ n:Int) -> Int
 3     {
 4         return count(m,n,0,1,1)
 5     }
 6     
 7     func count(_ m:Int,_ n:Int,_ used:Int,_ i1:Int,_ j1:Int) -> Int
 8     {
 9         var res:Int = m <= 0 ? 1 : 0
10         if n == 0 {return 1}
11         for i in 0..<3
12         {
13             for j in 0..<3
14             {
15                 var I:Int = i1 + i
16                 var J:Int = j1 + j
17                 var used2:Int = used | 1 << (i * 3 + j)
18                 let num1:Int = ((I % 2 == 0) || (J % 2 == 0) || (used2 == 0)) ? 1 : 0
19                 let num2:Int = 1 << (I / 2 * 3 + J / 2)
20                 if used2 > used && (num1 & num2) == 0
21                 {
22                     res += count(m - 1,n - 1,used2,i,j)
23                 }
24             }
25         }
26         return res
27     }
28 }

点击:Playground测试

1 var sol = Solution()
2 print(sol.numberOfPatterns(1,1))
3 //Print 9

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐