leetcode351.安卓系统手势(java):练习HashMap

题目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
分析
用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;
    }
}

参考力扣题解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值