LC 351. Android Unlock Patterns

学向勤中得,萤窗万卷书。这篇文章主要讲述LC 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:

  1. Each pattern must connect at least  m  keys and at most  n  keys.
  2. All the keys must be distinct.
  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. The order of keys used matters.
LC 351. Android Unlock Patterns

文章图片

思路:
【LC 351. Android Unlock Patterns】1. 求路径可行性,需要返回 —— 回溯
2. 用过的不能再用—— map
3. 下面是遍历1-9的做法,其实对称性可以看出1,3,7,9是一样的数量,2,4,6,8是一样数量,5单独一个数量。这样只用算三个数量即可。有时间实现。
1 class Solution { 2 public: 3 int numberOfPatterns(int m, int n) { 4if (m > 9 || m < 1 || n > 9 || n < 1) return 0; 5vector< int> path; 6int ret = 0; 7set< int> used; 8helper(m, n, path, used, ret); 9return ret; 10 } 11 void helper(int m, int n, vector< int> path, set< int> used, int& ret) { 12if (used.size() > = m & & used.size() < = n) ret++; 13if (used.size() == n) return; 14for (int i = 1; i < = 9; i++) { 15if(used.count(i)) continue; 16if (path.empty()) { 17path.push_back(i); 18used.insert(i); 19helper(m, n, path, used, ret); 20path.pop_back(); 21used.erase(i); 22} 23else { 24bool cond1 = path.back() % 2 == 1 & & i == 5; 25bool cond2 = path.back() == 5; 26bool cond3 = path.back() % 2 == 1 & & i % 2 == 1 & & path.back() != 5 & & used.count((path.back() + i) / 2) != 0; 27bool cond4 = path.back() % 2 == 1 & & i % 2 == 0; 28bool cond5 = path.back() % 2 == 0 & & (path.back() + i) / 2 == 5 & & used.count(5) != 0; 29bool cond6 = path.back() % 2 == 0 & & (path.back() + i) != 10; 30if (cond1 || cond2 || cond3 || cond4 || cond5 || cond6) { 31path.push_back(i); 32used.insert(i); 33helper(m, n, path, used, ret); 34path.pop_back(); 35used.erase(i); 36} 37} 38} 39 } 40 };

 

    推荐阅读