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.
| 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.
Solution1:Backtracking
总结见:http://www.jianshu.com/p/883fdda93a66
思路: 内层为Backtracking基本套路
Time Complexity: O(about (m-n) * 2^m) Space Complexity: O(N)
Solution2:DP
TBC
Solution1 Code:
public class Solution {
public int numberOfPatterns(int m, int n) {
// Skip array represents number to skip between two pairs
// just for check
int skip_table[][] = new int[10][10];
skip_table[1][3] = skip_table[3][1] = 2;
skip_table[1][7] = skip_table[7][1] = 4;
skip_table[3][9] = skip_table[9][3] = 6;
skip_table[7][9] = skip_table[9][7] = 8;
skip_table[1][9] = skip_table[9][1] = skip_table[2][8] = skip_table[8][2] = skip_table[3][7] = skip_table[7][3] = skip_table[4][6] = skip_table[6][4] = 5;
boolean visited[] = new boolean[10];
int result = 0;
// DFS search each length from m to n
for(int i = m; i <= n; ++i) {
result += DFS(visited, skip_table, 1, i - 1) * 4; // 1, 3, 7, 9 are symmetric
result += DFS(visited, skip_table, 2, i - 1) * 4; // 2, 4, 6, 8 are symmetric
result += DFS(visited, skip_table, 5, i - 1); // 5
}
return rst;
}
// cur: the current position
// remain: the steps remaining
int DFS(boolean visited[], int[][] skip_table, int cur, int remain) {
if(remain < 0) return 0;
if(remain == 0) return 1;
visited[cur] = true;
int result = 0;
for(int i = 1; i <= 9; ++i) {
// If visited[i] is not visited and (two numbers are adjacent or skip number is already visited)
if(!visited[i] && (skip_table[cur][i] == 0 || (visited[skip[cur][i]]))) {
result += DFS(visited, skip_table, i, remain - 1);
}
}
visited[cur] = false;
return result;
}
}