Formatted question description: https://leetcode.ca/all/351.html
351 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. Explanation: | 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. @tag-dp
Let’s take a look at what is illegal,
- First, 1 cannot go directly to 3, it must go through 2.
- For the same reason, there are 4 to 6, 7 to 9, 1 to 7, 2 to 8, 3 to 9,
- There are also diagonals that must pass through 5, such as 1 to 9, 3 to 7, etc.
Create a two-dimensional array
jumps to record whether there is an intermediate key between the two number keys,
Then use a one-bit array
visited to record whether a key has been visited.
Then use recursion to solve. First call the recursive function for 1, in the recursive function, traverse each number from 1 to 9 next, and then find if there is a
jump between them.
If next has not been visited, and jump is 0. Or jump has been visited. Call the recursive function to next.
- After the number of patterns of number 1 is calculated, since 1,3,7,9 are symmetrical, multiply by 4
- Then call the recursive function on the number 2.
- 2, 4, 6, 9 are also symmetrical, and then multiply by 4.
- Finally, call 5 separately, and then add up all of them to get the final result.