设为首页 加入收藏

TOP

Leetcode dfs Word Break II
2015-07-20 17:43:51 来源: 作者: 【 】 浏览:2
Tags:Leetcode dfs Word Break


Word Break II

Total Accepted: 15138 Total Submissions: 92228My Submissions

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

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"].



题意:
给定一个字符串和一个单词字典,找出可以用字典里的单词来分割这个字符串的各种组合。
思路:dfs
void dfs(int start, string partition);
start表示当前要分割的字符串s[start:],
设 k将 s分割为s[:k]和s[k:],则 0 < k <= s.size() 且 s[:k]存在字典dict中
按上面这样的思路直接做会超时,可采用dfs + 剪枝的思路
增加一个bool数组 possible[k] 表示字符串s[k:]是否可用字典里的单词来分割


unordered_set
  
    _dict;
vector
   
     res; vector
    
      possible; string _s; void dfs(int start, string partition){ if(start >= _s.size()){ res.push_back(partition.substr(1, partition.size() - 1)); return; } for(int k = start + 1; k <= _s.size(); ++k){ if(possible[k] && _dict.find(_s.substr(start, k - start)) != _dict.end()){ //剪枝 int size_before = res.size(); dfs(k , partition + " " + _s.substr(start, k - start)); if(res.size() == size_before) possible[k] = false; //剪枝 } } } vector
     
       wordBreak(string s, unordered_set
      
        &dict){ _dict = dict; _s = s; possible = vector
       
        (s.size() + 1, true); dfs(0, ""); return res; }
       
      
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇zoj 3811 Untrusted Patrol(BFS+.. 下一篇zoj3811Untrusted Patrol((bfs+并..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)
·2025年,JAVA还值得 (2025-12-25 09:24:16)
·用 C 语言或者限制使 (2025-12-25 08:50:05)
·C++构造shared_ptr为 (2025-12-25 08:50:01)