天天看點

[LeetCode] 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:

Each pattern must connect at least m keys and at most n keys.

All the keys must be distinct.

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.

The order of keys used matters.

[LeetCode] Android Unlock Patterns 安卓解鎖模式

Explanation:

Invalid move: <code>4 - 1 - 3 - 6 </code>

Line 1 - 3 passes through key 2 which had not been selected in the pattern.

Invalid move: <code>4 - 1 - 9 - 2</code>

Line 1 - 9 passes through key 5 which had not been selected in the pattern.

Valid move: <code>2 - 4 - 1 - 3 - 6</code>

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

Valid move: <code>6 - 5 - 4 - 1 - 9 - 2</code>

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:

這道題乍一看題目這麼長以為是一個設計題,其實不是,這道題還是比較有意思的,起碼跟實際結合的比較緊密。這道題說的是安卓機子的解鎖方法,有9個數字鍵,如果密碼的長度範圍在[m, n]之間,問所有的解鎖模式共有多少種,注意題目中給出的一些非法的滑動模式。那麼我們先來看一下哪些是非法的,首先1不能直接到3,必須經過2,同理的有4到6,7到9,1到7,2到8,3到9,還有就是對角線必須經過5,例如1到9,3到7等。我們建立一個二維數組jumps,用來記錄兩個數字鍵之間是否有中間鍵,然後再用一個一位數組visited來記錄某個鍵是否被通路過,然後我們用遞歸來解,我們先對1調用遞歸函數,在遞歸函數中,我們周遊1到9每個數字next,然後找他們之間是否有jump數字,如果next沒被通路過,并且jump為0,或者jump被通路過,我們對next調用遞歸函數。數字1的模式個數算出來後,由于1,3,7,9是對稱的,是以我們乘4即可,然後再對數字2調用遞歸函數,2,4,6,9也是對稱的,再乘4,最後單獨對5調用一次,然後把所有的加起來就是最終結果了,參見代碼如下:

解法一:

解法二:

繼續閱讀