繁体   English   中英

这种递归算法的时间复杂度是多少

[英]What's the time complexity of this recursive algorithm

这是一个算法问题:

给定字符串s和单词字典dict,请在s中添加空格以构建一个句子,其中每个单词都是有效的词典单词。

返回所有可能的句子。

例如,给定s =“ catsanddog”,dict = [“ cat”,“ cats”,“ and”,“ sand”,“ dog”]。

一个解决方案是[“猫和狗”,“猫沙狗”]。

解决方案如下,但是我很难确定此解决方案的时间复杂度。 有人可以给我一些提示吗,尤其是如果面试官在面试中问到这个时间的复杂性,有没有一种快速的方法可以在没有太多数学的情况下找到它?

public class Solution {
    Map<String,List<String>> map = new HashMap();
    public List<String> wordBreak(String s, Set<String> wordDict) {
        List<String> res = new ArrayList<String>();
        if(s == null || s.length() == 0) {
            return res;
        }
        if(map.containsKey(s)) {
            return map.get(s);
        }
        if(wordDict.contains(s)) {
            res.add(s);
        }
        for(int i = 1 ; i < s.length() ; i++) {
            String t = s.substring(i);
            if(wordDict.contains(t)) {
                List<String> temp = wordBreak(s.substring(0 , i) , wordDict);
                if(temp.size() != 0) {
                    for(int j = 0 ; j < temp.size() ; j++) {
                        res.add(temp.get(j) + " " + t);
                    }
                }
            }
        }
        map.put(s , res);
        return res;
    }
}

时间复杂度为O(2^n * n)

这种断字的最大次数是2^(n-1) ,对元向量长度为n-1双射 :对于两个字符之间的每个空格,您可以在该字符处断字(向量中的1)或不(向量中的0),为您提供2^(n-1)这样的可能单词。

由于创建了每个字符串,计算了其哈希并将其添加到集合中后,它是O(n) (子字符串的长度),因此得到O(2^n * n)

您会遇到以下最坏的情况:

dict = [a, aa, aaa, aaaa, ....]
s = "aaaaaaaaa...a"

您的map可确保您不会使用备忘录来做重复的工作。 (否则,复杂度将是n阶乘,但是使用它可以避免重复的工作,例如从头开始重新计算前缀“ aaa ... a | a | a”和“ aa ... a | aa”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM