难题
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 }