zoukankan      html  css  js  c++  java
  • 291. Word Pattern II

    DFS+BACKTRACK
    没弄些乱七八糟的符号什么的在test case算是脱离低级趣味了。

    这个题就是正常的划分string,连二段brach都不是。 我只进行了最基础的剪枝,有很多剪枝条件,比如剩余string < pattern之类的。。

    一开始每次循环都建2个MAP保存信息以便回溯,结果破了纪录。
    image
    这辈子没离0这么接近过。。

    换成简单的remove,就好多了。
    Tn = T(n-1) + T(n-2) + ... + T(1)
    T(n-1) = T(n-2) + ... + T(1)
    T(n) = 2T(n-1) = 4T(n-2) = 2^n T(1)

    Time Complexity: O(2^n)
    Space Complexity: O(n)

    public class Solution {
        public boolean wordPatternMatch(String pattern, String str) {
            if (pattern.length() == 0 && str.length() == 0) return true;
            Map<Character, String> map1 = new HashMap();
            Map<String, Character> map2 = new HashMap();
            return dfs(map1, map2, pattern, str, 0, 0);
        }
        
        public boolean dfs(Map<Character, String> map1, Map<String, Character> map2, String pattern, String str, int chPos, int strPos) {
            if (chPos == pattern.length() && strPos == str.length()) {
                return true;
            } else if (chPos >= pattern.length() || strPos >= str.length()) {
                return false;
            } else {
    
                char c = pattern.charAt(chPos);
                for (int i = strPos; i < str.length(); i++) {
                    String tempS = str.substring(strPos, i+1);
                    if (!map1.containsKey(c) && !map2.containsKey(tempS)) {
                        map1.put(c, tempS);
                        map2.put(tempS, c);
                        if (dfs(map1, map2, pattern, str, chPos+1, i+1)) return true;
                        map1.remove(c);
                        map2.remove(tempS);
                    } else if (!map1.containsKey(c) || !map2.containsKey(tempS)) {
                        continue;
                    } else {
                        if (map1.get(c).equals(tempS) && map2.get(tempS) == c) {
                            if (dfs(map1, map2, pattern, str, chPos+1, i+1)) return true;
                        } else {
                            continue;
                        }
                    }
    
                }
                return false;
            }
        }
    }
    
  • 相关阅读:
    从新浪财经获取金融新闻类数据并进行打分计算
    SQL窗口函数的用法总结
    从新浪财经获取金融新闻类数据并保存到MySQL
    [ZJOI2015]幻想乡战略游戏
    二次剩余入门
    [多校赛20210406]迫害 DJ
    [NOI Online 2021 提高组] 愤怒的小N
    [NOI Online 2021 提高组] 岛屿探险
    「UNR #3」百鸽笼
    [ZJOI2019]开关
  • 原文地址:https://www.cnblogs.com/reboot329/p/6056155.html
Copyright © 2011-2022 走看看