在最近的一次工作面试中,我被要求给出以下问题的解决方案:
给定一个字符串s(没有空格)和一个字典,返回字典中组成字符串的单词。
例如,s= peachpie, dic= {peach, pie}, result={peach, pie}。
我会问这个问题的决策变化:
如果
s可以由字典中的单词组成,则返回yes,否则返回no。
我对此的解决方案是回溯(用 Java 编写)
public static boolean words(String s, Set<String> dictionary)
{
    if ("".equals(s))
        return true;
    for (int i=0; i <= s.length(); i++)
    {
        String pre = prefix(s,i); // returns s[0..i-1]
        String suf = suffix(s,i); // returns s[i..s.len]
        if (dictionary.contains(pre) && words(suf, dictionary))
            return true;
    }
    return false;
}
public static void main(String[] args) {
    Set<String> dic = new HashSet<String>();
    dic.add("peach");
    dic.add("pie");
    dic.add("1");
    System.out.println(words("peachpie1", dic)); // true
    System.out.println(words("peachpie2", dic)); // false
}
这个解决方案的时间复杂度是多少?我在 for 循环中递归调用,但只针对字典中的前缀。
有任何想法吗?