题目
分析
用hashmap记录从某个按键要划到另一个按键时要经过的键。
比如1:{(3,2),(7,4),(9,4)};
可以发现1,3,7,9是等效的,2,4,6,8是等效的,所以只需要计算一次路径,乘4即可
用一个boolean数组记录该按键是否被连过,如果连过,则可以经过,否则不可以经过。
具体代码
import java.util.HashMap;
class Solution {
private boolean used[];
private HashMap<Integer,HashMap<Integer,Integer>> map;
private int m,n;
public int numberOfPatterns(int m, int n) {
used = new boolean[10];
this.m = m;
this.n = n;
map = new HashMap<>();
map.put(1,new HashMap<>(){
{
put(3,2);
put(7,4);
put(9,5);
}
});
map.put(2,new HashMap<>(){{
put(8,5);
}});
map.put(3,new HashMap<>(){{
put(1,2);
put(7,5);
put(9,6);
}});
map.put(4,new HashMap<>(){{
put(6,5);
}});
map.put(5,new HashMap<>());
map.put(6,new HashMap<>(){{
put(4,5);
}});
map.put(7,new HashMap<>(){{
put(1,4);
put(3,5);
put(9,8);
}});
map.put(8,new HashMap<>(){{
put(2,5);
}});
map.put(9,new HashMap<>(){{
put(7,8);
put(3,6);
put(1,5);
}});
int res = 0;
res += 4*dfs(1,1);
res += 4*dfs(2,1);
res += dfs(5,1);
return res;
}
public int dfs(int pos,int path){
if(used[pos]){
return 0;
}
if(path == n){
return 1;
}
int res = path>=m?1:0;
used[pos] = true;
for(int next = 1;next <=9;next++){
if(!map.get(pos).containsKey(next)||used[map.get(pos).get(next)]){
res += dfs(next,path+1);
}
}
used[pos] = false;
return res;
}
}
参考力扣题解