【63】140. Word Break II

140. Word Break II

Description Submission Solutions Add to List

  • Total Accepted: 79139
  • Total Submissions: 353953
  • Difficulty: Hard
  • Contributors: Admin

 

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. You may assume the dictionary does not contain duplicate words.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

 
class Solution {
public:
//经典dfs,但需要用到possible[i] = true表示在[i, n]区间上有解,n为s的长度 来剪枝优化。如果possible是false就不需要找下去了。
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        int n = s.size();
        vector<string> res;
        string level;
        vector<bool> possible(n, true);
        unordered_set<string> dict;
        for(string s : wordDict){
            dict.insert(s);
        }
        dfs(s, dict, possible, res, level, 0);
        return res;
    }
    
    void dfs(string s, unordered_set<string>& dict, vector<bool>& possible, vector<string>& res, string& level, int start){
        if(start == s.size()){
            res.push_back(level.substr(0, level.size() - 1));
            //return;//有没有都可以
        }
        for(int i = start; i < s.size(); i++){
            string w = s.substr(start, i - start + 1);
            if(possible[i] && dict.find(w) != dict.end()){
                level.append(w).append(" ");
                int size = res.size();
                dfs(s, dict, possible, res, level, i + 1);
                if(res.size() == size){
                    possible[i] = false;
                    //level.resize(level.size() - w.size() - 1);
                }
                level.resize(level.size() - w.size() - 1);//无论怎样level都要resize的
            }
            
            
        }
    }
};

 

 
 
posted @ 2017-02-12 16:20  会咬人的兔子  阅读(189)  评论(0编辑  收藏  举报