140. Word Break II (backtracking)

Latest:

Time complexity: O(2^n)

The algorithm explores all possible ways to break the string into words. 
In the worst case, where each character can be treated as a word, the recursion tree has 2^n
leaf nodes, resulting in an exponential time complexity.

Space complexity: O(2^n)
class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        Set<String> wordSet = new HashSet<>();
        for (String w : wordDict) {
            wordSet.add(w);
        }
        List<List<String>> result = new ArrayList<>();
        backtracking(0, s, wordSet, new ArrayList<>(), result);

        List<String> res = new ArrayList<>(); 
        for (List<String> list : result) {
            StringBuilder sb = new StringBuilder();
            for (String str : list) {
                sb.append(str).append(" ");
            }
            sb.deleteCharAt(sb.length()-1);
            res.add(sb.toString());
        }
        return res;
    }
    private void backtracking(int start, String s, Set<String> wordSet, List<String> list, List<List<String>> result) {
        if (start == s.length()) {
            result.add(new ArrayList<>(list));
        }
        for (int i = start; i < s.length(); i++) {
            String substr = s.substring(start, i+1);
            if (wordSet.contains(substr)) {
                list.add(substr);
                backtracking(i+1, s, wordSet, list, result);
                System.out.println(list);
                list.remove(list.size()-1);
            }
        }
    }
}
/***
Time complexity: O(2^n)

The algorithm explores all possible ways to break the string into words. 
In the worst case, where each character can be treated as a word, the recursion tree has 2^n
leaf nodes, resulting in an exponential time complexity.

Space complexity: O(2^n)

catsanddog

i == s.length


    catsand
      /\   
  cat    cats    
    /.    \
  sand    and


  catsand = cat + f(3,xx) = cat + sand
          = cats + f(4, xx) = cats + and

start dfs on i index(0 1 2 is cat), pass dfs(i+1) = dfs(3)  to next dfs
[cat, sand, dog] -> execute dfs() to end
list.remove(list.size()-1); // bactracking
[cat, sand]
list.remove(list.size()-1);
[cat]
list.remove(list.size()-1);
[]

backtrack to original i index(3), start to run again.. 
then find cats (index = 0 1 2 3) is ok, so pass dfs(i+1) = dfs(4)  to next dfs
[cats, and, dog] -> execute dfs() to end
list.remove(list.size()-1);
[cats, and]
list.remove(list.size()-1);
[cats]      
list.remove(list.size()-1);
[]
 */

O(2^N * MN)

use dfs + memo

time compexity is O(n^4... almost like backtracking

Last updated

Was this helpful?