★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-durcpixx-gp.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.android
Rules for a valid pattern:git
Explanation:github
| 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 patternthis
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.spa
Example:
Given m = 1, n = 1, return 9.code
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.htm
给定一个android 3x3密钥锁屏和两个整数m和n,其中1≤m≤n≤9,计算android锁屏的解锁模式总数,该解锁模式由最小M个密钥和最大N个密钥组成。
有效模式的规则:
说明:
| 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