★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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