給定一個非空字符串 s 和一個包含非空單詞列表的字典 wordDict,在字符串中增加空格來構建一個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。
說明:
分隔時可以重復使用字典中的單詞。
你可以假設字典中沒有重復的單詞。
示例 1:
輸入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
輸出:
[
“cats and dog”,
“cat sand dog”
]
代碼
class Solution {List<String> stringList=new ArrayList<>(); Set<Integer> check=new HashSet<>();int maxLen=0,minLen=Integer.MAX_VALUE;public List<String> wordBreak(String s, List<String> wordDict) {for(String word:wordDict)//獲取單詞的長度范圍,限制可選擇的長度{maxLen= Math.max(maxLen,word.length());minLen= Math.min(minLen,word.length());}wBreak(s,0,wordDict,new ArrayList<>());return stringList;}public void wBreak(String s,int pos,List<String> wordDict,List<String> list) {if(pos==s.length())//邊界{stringList.add( String.join(" ",list));return;}if(check.contains(pos))return;int resL=stringList.size();for(int i=minLen;i+pos<=s.length()&&i<=maxLen;i++){String sub=s.substring(pos,pos+i);for(String word:wordDict)//遍歷單詞{if(sub.equals(word)){list.add(word);wBreak(s,i+pos,wordDict,list);list.remove(list.size()-1);//回溯}}}if(stringList.size()==resL)//結果序列沒有變,說明該位置往后無法產生結果check.add(pos);}
}