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 mostn
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
Example1
Input: m = 1, n = 1
Output: 9
Example2
Input: m = 1, n = 2
Output: 65
分析
这道题目很容易想的比较复杂,其实是一个典型的DFS的题目,利用搜索加set即可解决。
如果要求k个node的结果,可以以所有的点为起点,将起点加入到visit中,然后求k-1个node的结果。在遍历的过程中,如果一个node已经在visit中,直接跳过,每次准备遍历该node时,需要结合visit判断一下该点与当前的node的连线是否有效。如果无效,直接跳过。
Code
class Solution {
public:
/**
* @param m: an integer
* @param n: an integer
* @return: the total number of unlock patterns of the Android lock screen
*/
int numberOfPatterns(int m, int n) {
// Write your code here
int sum = 0;
for (int i = m; i <= n; i ++)
{
set<int> visit;
for (int j = 1; j <= 9; j ++)
{
visit.insert(j);
int tmp = getCount(j, i-1, visit);
sum += tmp;
visit.erase(j);
}
}
return sum;
}
int getCount(int start, int left, set<int> visit)
{
if (left == 0)
return 1;
int sum = 0;
for (int i = 1; i <= 9; i ++)
{
if (visit.find(i) != visit.end())
continue;
if (isValid(start, i, visit))
{
visit.insert(i);
sum += getCount(i, left-1, visit);
visit.erase(i);
}
}
return sum;
}
bool isValid(int start, int end, set<int> visit)
{
if (start %2 == 0 && end % 2 == 0 && (start+end) == 10)
{
if (visit.find(5) == visit.end())
return false;
}
if ((start == 1 || start == 3 || start == 7 || start == 9)
&& (end == 1 || end == 3 || end == 7 || end == 9))
{
if (visit.find((start+end)/2) == visit.end())
return false;
}
return true;
}
};
运行效率
Your submission beats 15.29% Submissions!