Android Unlock Patterns

https://leetcode.com/problems/android-unlock-patterns/description/

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

Thoughts

搜索从一点开始走m - 1~ n-1步所有可能性即可. 有些点不能走, 要判断一下.

Code

class Solution {
    private int dfs(int[][] pass, int pos, boolean[] visited, int remainSteps) {
        if (remainSteps < 0) {
            return 0;
        } else if (remainSteps == 0) {
            return 1;
        }

        int res = 0;
        visited[pos] = true;
        for (int i = 1; i <= 9; i++) {
            if (visited[i] || !visited[pass[pos][i]]) {
                continue;
            }
            res += dfs(pass, i, visited, remainSteps - 1);
        }
        visited[pos] = false;
        return res;
    }

    public int numberOfPatterns(int m, int n) {
        int[][] pass = new int[10][10];
        pass[1][3] = pass[3][1] = 2;
        pass[1][7] = pass[7][1] = 4;
        pass[3][9] = pass[9][3] = 6;
        pass[7][9] = pass[9][7] = 8;
        pass[1][9] = pass[9][1] = pass[2][8] = pass[8][2] = pass[3][7] = pass[7][3] = pass[4][6] = pass[6][4] = 5;
        boolean[] visited = new boolean[10];
        visited[0] = true;
        int res = 0;
        for (int i = m; i <= n; i++) {
            res += dfs(pass, 1, visited, i - 1) * 4; // 1, 3, 7, 9
            res += dfs(pass, 2, visited, i - 1) * 4; // 2, 4, 6, 8
            res += dfs(pass, 5, visited, i - 1);
        }
        return res;
    }
}

Analysis

时间复杂度O(N!). 由于一个节点只能访问一次, sum_m^n 9!/(9 - i)! 空间O(N), 用于递归stack.

Last updated