140. Word Break II

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> result = new ArrayList<>();
        dfs(s, wordDict, 0, new ArrayList<>(), result);
        return result;
    }
    private void dfs(String s, List<String> wordDict, int start, List<String> list, List<String> res) {
        if (start == s.length()) {
            res.add(String.join(" ", list));
            return;
        }
        for (String w : wordDict) {
            int len = w.length(); // 我覺得很難想的是這個, 用 w 的 len 去抓 string 來比較, 但這樣的確很高效...
            if (start + len > s.length()) {
                continue;
            }
            String cur = s.substring(start, start + len);
            if (!w.equals(cur)) {
                continue;
            }
            
            // 如果比對後是存在 wordDict 沒錯的話(滿足 prefix), 就加入 list
            list.add(w);
            dfs(s, wordDict, start + len, list, res); // next substring part
            list.remove(list.size()-1); // backtracking
        }
    }
}

backtracking 2

use each index for substring

Last updated

Was this helpful?