• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Word Break II

难题

 

 1 class Solution {
 2 public:
 3     void dfs(string s, vector<string> &tmp, vector<string> &res, unordered_set<string> &unused, unordered_set<string> &dict) {
 4         if (s.size() == 0) {
 5             string ans = "";
 6             for (int i = 0; i < tmp.size(); i++) {
 7                 if (i == 0) ans += tmp[i];
 8                 else ans += " " + tmp[i];
 9             }
10             res.push_back(ans);
11             return;
12         }
13         if (unused.find(s) != unused.end()) return;
14         int pre = res.size();
15         for (int i = 1; i <= s.size(); i++) {
16             if (dict.find(s.substr(0, i)) != dict.end()) {
17                 tmp.push_back(s.substr(0, i));
18                 dfs(s.substr(i, s.size()-i), tmp, res, unused, dict);
19                 tmp.pop_back();
20             }
21         }
22         if (res.size() == pre) unused.insert(s);
23     }
24     vector<string> wordBreak(string s, unordered_set<string> &dict) {
25         vector<string> res;
26         unordered_set<string> unused;
27         vector<string> tmp;
28         dfs(s, tmp, res, unused, dict);
29         return res;
30     }
31 };

 C#

 1 public class Solution {
 2     public List<string> WordBreak(string s, ISet<string> wordDict) {
 3         List<string> ans = new List<string>();
 4         HashSet<string> unused = new HashSet<string>();
 5         List<string> tmp = new List<string>();
 6         dfs(s, ref tmp, ref ans, ref unused, wordDict);
 7         return ans;
 8     }
 9     public void dfs(string s, ref List<string> tmp, ref List<string> ans, ref HashSet<string> unused, ISet<string> wordDict) {
10         if (s.Length == 0) {
11             string res = "";
12             for (int i = 0; i < tmp.Count; i++) {
13                 if (i == 0) res += tmp[i];
14                 else res += " " + tmp[i];
15             }
16             ans.Add(res);
17             return;
18         }
19         if (unused.Contains(s) == true) return;
20         int pre = ans.Count;
21         for (int i = 1; i <= s.Length; i++) {
22             if (wordDict.Contains(s.Substring(0, i))) {
23                 tmp.Add(s.Substring(0, i));
24                 dfs(s.Substring(i, s.Length-i), ref tmp, ref ans, ref unused, wordDict);
25                 tmp.RemoveAt(tmp.Count-1);
26             }
27         }
28         if (ans.Count == pre) unused.Add(s);
29     }
30 }
View Code

 

posted @ 2014-01-16 12:06  ying_vincent  阅读(137)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3