351 Android Unlock Patterns

1. Question

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. 1.
    Each pattern must connect at least m keys and at most n keys.
  2. 2.
    All the keys must be distinct.
  3. 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. 4.
    The order of keys used matters.
Explanation:
1
| 1 | 2 | 3 |
2
| 4 | 5 | 6 |
3
| 7 | 8 | 9 |
Copied!
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.

2. Implementation

(1) Backtracking
1
public class Solution {
2
public int numberOfPatterns(int m, int n) {
3
// Skip represents the number to skip between two numbers
4
int[][] skip = new int[10][10];
5
skip[1][3] = skip[3][1] = 2;
6
skip[7][9] = skip[9][7] = 8;
7
skip[1][7] = skip[7][1] = 4;
8
skip[3][9] = skip[9][3] = 6;
9
skip[1][9] = skip[9][1] = skip[3][7] = skip[7][3] = skip[2][8] = skip[8][2]
10
= skip[4][6] = skip[6][4] = 5;
11
12
boolean[] visited = new boolean[10];
13
int res = 0;
14
for (int i = m; i <= n; i++) {
15
res += searchPatterns(visited, skip, 1, i - 1) * 4; // 1, 3, 7, 9 are symmetric
16
res += searchPatterns(visited, skip, 2, i - 1) * 4; // 2, 4, 6, 8 are symmetric
17
res += searchPatterns(visited, skip, 5, i - 1);
18
}
19
return res;
20
}
21
22
public int searchPatterns(boolean[] visited, int[][] skip, int curNum, int steps) {
23
if (steps == 0) {
24
return 1;
25
}
26
27
visited[curNum] = true;
28
int res = 0;
29
for (int nextNum = 1; nextNum <= 9; nextNum++) {
30
// if nextNum is not visited and (curNum is adjacent to nextNum or their skip number is visited)
31
if (!visited[nextNum] && (skip[curNum][nextNum] == 0 || visited[skip[curNum][nextNum]])) {
32
res += searchPatterns(visited, skip, nextNum, steps - 1);
33
}
34
}
35
visited[curNum] = false;
36
return res;
37
}
38
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!), n是pattern的最长长度 ,空间复杂度O(n), 递归的深度最多为n