With the following algorithm (from Leetcode):
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given s = "leetcode", dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
The naive solution is given as follows:
public class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return word_Break(s, new HashSet(wordDict), 0);
}
public boolean word_Break(String s, Set<String> wordDict, int start) {
if (start == s.length()) {
return true;
}
for (int end = start + 1; end <= s.length(); end++) {
if (wordDict.contains(s.substring(start, end)) && word_Break(s, wordDict, end)) {
return true;
}
}
return false;
}
}
The time complexity is listed as O(n^n) because that's how big the recursive tree goes. I totally agree that the last level of the recursion tree has N^N elements, but doesn't the one before that level have N^(N-1)? So we're looking at N^N + N^(N-1) + N^(N-2)... resulting in a much higher time complexity correct?




word_Breakprivate? Also,N^N + N^(N-1) + ...is a geometric series which givesO(N^(N+1))- meowgoesthedog