中级农民
积分 113
大米 颗
鳄梨 个
水井 尺
蓝莓 颗
萝卜 根
小米 粒
学分 个
注册时间 2015-3-15
最后登录 1970-1-1
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
正在复习
https://leetcode.com/problems/word-break-ii/
对于时间复杂度的分析有些疑问
1.
我自己的解法, dp, dp[i] store all possible sentences to form str[0,i-1]
public List<String> wordBreak(String s, List<String> wordDict) {
List<String> [] dp = new ArrayList[s.length() + 1];
Set<String> dictSet = new HashSet<>(wordDict);
List<String> res = new ArrayList<>();
//dp[i] : all possbile sentences to form s[0,i-1];
for (int i = 0; i < dp.length; i++) {
dp[i] = new ArrayList<>();
}
dp[0].add("");
for (int i = 1; i < dp.length; i++) {
for (int start = 0; start < i; start++) {
//when index operation is meesy, conisder a 1-element or 2-element case to test
String substr = s.substring(start, i);
if (!dp[start].isEmpty() && wordDict.contains(substr)) {
for (String prefix : dp[start]) {
dp[i].add(prefix + " " + substr);
}
}
}
}
for (String sentence : dp[dp.length - 1]) {
if (sentence.length() >= 1)
res.add(sentence.substring(1));
}
return res;
} 复制代码
自己能确定的是 first loop O(n) * substring cost O(n), but can't decide time cost of nested loop ( for (String prefix : dp[start])
各位大佬能帮着看下吗.
2. lc 上 最快解法
public List<String> wordBreak(String s, List<String> wordDict) {
if (s.length() > 100) {
return new ArrayList();
}
List<String> result = new ArrayList<String> ();
wordBreakUtil(s, wordDict, result, new StringBuilder());
return result;
}
public void wordBreakUtil(String s, List<String> wordDict, List<String> result, StringBuilder subList) {
// add " " between 2 words in subList
if (subList.length() != 0) {
subList.append(" ");
}
// iterate over all the words in wordDict
for (String word: wordDict) {
if (s.startsWith(word)) {
StringBuilder sb = new StringBuilder(subList);
// append current match in sb
sb.append(word);
// if this is last word to be matched
if (s.equals(word)) {
result.add(new String(sb));
} else {
wordBreakUtil(s.substring(word.length()), wordDict, result, sb);
}
}
}
} 复制代码 这个解法是在loop against wordDict, can perfect solve a very tricky test case on lc(which cause many other solution TLE)
我不是很确定这个解法的时间复杂度,分析是, O (len(s) ^ len(wordDict)). 理由是for each recursion node in recursion tree, loops by wordDict, so each recursion has len(wordDict) branches, and whole recursion tree has height len(s)
请大佬们帮忙看看
上一篇:
讨论个看到过多次的面经题 下一篇:
股票问题IV中如何把3维DP数组转化为2维数组