140. Word Break II

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

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 + backtracking

public class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> res = new ArrayList<>();
        if(s == null || s.length() == 0) return res;
        List<String> cur = new ArrayList<>();
        Set<String> dict = new HashSet<>(wordDict);
        dfs(s, 0, cur, res, dict);
        return res;
    }
    
    private void dfs(String s, int pos, List<String> cur, List<String> res,
            Set<String> dict){
        if(pos == s.length()){
            String str = listToString(cur);
            res.add(str);
            return;
        }


        for(int i=pos; i<s.length(); i++){
            if(!dict.contains(s.substring(pos, i+1))) continue;
            cur.add(s.substring(pos, i+1));
            dfs(s, i+1, cur, res, dict);
            cur.remove(cur.size()-1);
        }
    }
    
    private String listToString(List<String> list){
        StringBuilder sb = new StringBuilder();
        //sb.append("\"");
        for(int i=0; i<list.size()-1; i++){
            sb.append(list.get(i));
            sb.append(" ");
        }
        sb.append(list.get(list.size()-1));
        //sb.append("\"");
        return sb.toString();
    }
}

但是在遇到
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
會出現(xiàn)超時的問題喂急,因?yàn)橛袩o數(shù)種排列組合。于是用dp來存儲已經(jīng)求得的解笛求。這里的dp不是array而是Map<String, LinkedList<String>> map

public class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
       return dfs(s, new HashSet<String>(wordDict), new HashMap<String, LinkedList<String>>());
    }
    
   List<String> dfs(String s, Set<String> wordDict, HashMap<String, LinkedList<String>> map){
       if(map.containsKey(s))
           return map.get(s);
       
       LinkedList<String> res = new LinkedList<String>();
       if(s.length() == 0){
           res.add("");
           return res;
       }
       
       for(String word : wordDict){
           if(s.startsWith(word)){
               //remove the word length
               List<String> sublist = dfs(s.substring(word.length()), wordDict, map);
               for(String sub : sublist){
                   res.add(word + (sub.isEmpty()? "" : " ") + sub);
               }
           }
       }
       map.put(s, res);
       return res;
   }
    
}

二刷
思路同上

public class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        Set<String> dict = new HashSet<>(wordDict);
        Map<String, List<String>> cache = new HashMap<>();
        return dfs(s, cache, dict);
    }
    
    private List<String> dfs(String s, Map<String, List<String>> cache, Set<String> dict){
        if(cache.containsKey(s)) return cache.get(s);
        
        LinkedList<String> res = new LinkedList<>();
        if(s.length()==0){
            res.add("");
            return res;
        }
        
        for(String word : dict){
            if(s.startsWith(word)){
                List<String> sublist = dfs(s.substring(word.length()), cache, dict);
                for(String sub : sublist){
                    if(sub.isEmpty()){
                        res.add(word + sub);
                    }
                    else res.add(word + " " + sub);
                }
            }
        }
        cache.put(s, res);
        return res;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末廊移,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子探入,更是在濱河造成了極大的恐慌狡孔,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蜂嗽,死亡現(xiàn)場離奇詭異苗膝,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)徒爹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門荚醒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人隆嗅,你說我怎么就攤上這事界阁。” “怎么了胖喳?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵泡躯,是天一觀的道長。 經(jīng)常有香客問我丽焊,道長较剃,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任技健,我火速辦了婚禮写穴,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘雌贱。我一直安慰自己啊送,他們只是感情好偿短,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著馋没,像睡著了一般昔逗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上篷朵,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天勾怒,我揣著相機(jī)與錄音,去河邊找鬼声旺。 笑死笔链,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艾少。 我是一名探鬼主播卡乾,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼翼悴,長吁一口氣:“原來是場噩夢啊……” “哼缚够!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起鹦赎,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤谍椅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后古话,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體雏吭,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年陪踩,在試婚紗的時候發(fā)現(xiàn)自己被綠了杖们。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡肩狂,死狀恐怖摘完,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情傻谁,我是刑警寧澤孝治,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站审磁,受9級特大地震影響谈飒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜态蒂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一杭措、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧钾恢,春花似錦手素、人聲如沸吕喘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽氯质。三九已至,卻和暖如春祠斧,著一層夾襖步出監(jiān)牢的瞬間闻察,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工琢锋, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留辕漂,地道東北人。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓吴超,卻偏偏與公主長得像钉嘹,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鲸阻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容