Algo-Sim › Recursion & Backtracking

Word Break II

Hard · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Every way to split a string into dictionary words: backtrack over the first word, memoising the sentences of each suffix.

Problem

Given a string s and a dictionary wordDict, add spaces to s to build every sentence in which each word is in the dictionary. Return all such sentences in any order. A word may be reused.

Constraints

Edge cases to test

Follow-up questions

Why memoise suffixes?
The same suffix is reached by many prefixes; memoising its sentences avoids recomputing them, though the output can still be exponential.
How do you fail fast?
Run Word Break’s O(n²) boolean DP first and skip the search when it says no.

Solution

Java

Map<Integer, List<String>> memo = new HashMap<>();

List<String> wordBreak(String s, List<String> wordDict) {
    return dfs(s, 0, new HashSet<>(wordDict));
}

// Every sentence that spells s[start..].
List<String> dfs(String s, int start, Set<String> dict) {
    if (memo.containsKey(start)) return memo.get(start);
    List<String> out = new ArrayList<>();
    if (start == s.length()) {
        out.add("");
        return out;
    }
    for (int end = start + 1; end <= s.length(); end++) {
        String word = s.substring(start, end);
        if (!dict.contains(word)) continue;
        for (String rest : dfs(s, end, dict))
            out.add(rest.isEmpty() ? word : word + " " + rest);
    }
    memo.put(start, out);
    return out;
}

Python

def word_break(s, word_dict):
    words = set(word_dict)
    memo = {}

    # Every sentence that spells s[start:].
    def dfs(start):
        if start in memo:
            return memo[start]
        if start == len(s):
            return [""]
        out = []
        for end in range(start + 1, len(s) + 1):
            word = s[start:end]
            if word not in words:
                continue
            for rest in dfs(end):
                out.append(word + " " + rest if rest else word)
        memo[start] = out
        return out

    return dfs(0)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    unordered_map<int, vector<string>> memo;

    vector<string> wordBreak(string &s, vector<string> &wordDict) {
        unordered_set<string> dict(wordDict.begin(), wordDict.end());
        return dfs(s, 0, dict);
    }

    // Every sentence that spells s[start..].
    vector<string> dfs(string &s, int start, unordered_set<string> &dict) {
        if (memo.count(start)) return memo[start];
        vector<string> out;
        if (start == int(s.size())) {
            out.push_back("");
            return out;
        }
        for (int end = start + 1; end <= int(s.size()); end++) {
            string word = s.substr(start, end - start);
            if (!dict.count(word)) continue;
            for (string &rest : dfs(s, end, dict))
                out.push_back(rest.empty() ? word : word + " " + rest);
        }
        memo[start] = out;
        return out;
    }
};

More Recursion & Backtracking problems