DP

作者: 王鑫鑫_d516 | 来源:发表于2019-05-19 12:32 被阅读0次

WordBreak
solution DFS +MM

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<>(wordDict);
        Boolean[] mm = new Boolean[s.length()];
        return this.helper(s, set, 0, mm);
    }
    
    public boolean helper(String s, Set<String> set, int start, Boolean[] mm) {
        if (start == s.length()) {
            return true;
        }
        
        if (mm[start] != null) {
            return mm[start];
        }
        
        for (int e = start + 1; e <= s.length(); ++ e) {
            if (set.contains(s.substring(start, e)) && helper(s, set, e, mm)) {
                return mm[start] = true;
            }
        }
        return mm[start] = false;
    }
}

solution 2

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<>(wordDict);
        int n = s.length() + 1;
        boolean[] dp = new boolean[n];
        dp[0] = true;
        for (int i = 1; i < n; ++ i) {
            for (int j = 0; j < i; ++ j) {
                if (dp[j] &&
                   set.contains(s.substring(j, i)) ) {
                    dp[i] = true;
                    break;
                }
            }
            
        }
        return dp[s.length()];
    }
}

WordBreakII

class Solution {
    Map<Integer, List<String>> map = new HashMap<>();
    public List<String> wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<>(wordDict);
        return helper(s, set, 0);
    }
    
    public List<String> helper(String s, Set<String> set, int start) {
        if (map.containsKey(start)) {
            return map.get(start);
        }
        LinkedList<String> res = new LinkedList<>();
        if (start == s.length()) {
            res.add("");
        }
        
        for (int end = start + 1; end <= s.length(); ++ end) {
            if (set.contains(s.substring(start, end))) {
                List<String> tmp = helper(s, set, end);
                
                for (String t : tmp) {
                    res.add(s.substring(start, end) + (t.equals("") ? "" : " ") + t);
                } 
            }
        }
        
        map.put(start, res);
        return res;
    }
}

相关文章

网友评论

      本文标题:DP

      本文链接:https://www.haomeiwen.com/subject/dqofzqtx.html