140. Word Break II

140. Word Break II

 

dfs + memo

Word break ii 

Return all the answers 

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




class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        HashMap<String, List<String>> used = new HashMap<>();
        HashSet<String> set = new HashSet<>();
        List<String> res = new ArrayList<>();
        
        for(String word : wordDict){
            set.add(word);
        }
        
        res = helper(s, set, used);
        return res;
    }
    public List<String> helper(String s, HashSet<String> set, HashMap<String, List<String>> used){
        if(used.containsKey(s)){
            return used.get(s);
        }
        
        if(s.length() == 0){
            return null;
        }
        List<String> res = new ArrayList<>();
        for(int i = 1; i <= s.length(); i++){
            String sub = s.substring(0, i);
            List<String> partRes = null;
            if(set.contains(sub)){
                partRes = helper(s.substring(i), set, used);
                if(partRes == null){
                    res.add(sub);
                }else{
                    for(String str : partRes){
                        res.add(sub + " " + str); // " ". not ""
                    }
                }
            }
        }
        used.put(s, res);
        return res;
    }
}

 

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]

posted on 2018-08-10 15:26  猪猪&#128055;  阅读(142)  评论(0)    收藏  举报

导航