140. Word Break II
作者:互联网
My back tracking solution1:
class Solution { List<String> res = new ArrayList<>(); Set<String> set = new HashSet<>(); public List<String> wordBreak(String s, List<String> wordDict) { for(String word:wordDict){ set.add(word); } List<String> list = new ArrayList<>(); backTracking(s, 0, list); return res; } private void backTracking(String s, int index, List<String> list){ if(index==s.length()){ StringBuilder temp = new StringBuilder(); for(String word: list){ temp.append(word+" "); } temp.deleteCharAt(temp.length()-1); res.add(temp.toString()); return; } for(int i=index+1;i<s.length()+1;i++){ String word = s.substring(index,i); if(set.contains(word)){ list.add(word); backTracking(s, i, list); list.remove(list.size()-1); } } } }
My back tracking solution2:
class Solution { List<String> res = new ArrayList<>(); Set<String> set = new HashSet<>(); public List<String> wordBreak(String s, List<String> wordDict) { for(String word:wordDict){ set.add(word); } List<String> list = new ArrayList<>(); backTracking(s, wordDict, list); return res; } private void backTracking(String s, List<String> wordDict, List<String> list){ if(s.length()==0){ StringBuilder temp = new StringBuilder(); for(String word: list){ temp.append(word+" "); } temp.deleteCharAt(temp.length()-1); res.add(temp.toString()); return; } for(String word: wordDict){ if(s.startsWith(word)){ list.add(word); backTracking(s.substring(word.length()), wordDict, list); list.remove(list.size()-1); } } } }
标签:II,Word,String,temp,List,list,Break,wordDict,word 来源: https://www.cnblogs.com/feiflytech/p/16133361.html