追溯算法是否必须从后面开始?

时间:2014-10-10 12:23:31

标签: algorithm backtracking

我通过回溯算法解决了wordbreakII问题here。 以下是代码:

public static List<String> wordBreak(String s, Set<String> dict) {
    List<String> words = new ArrayList<String>();
    int len = s.length();
    for (int i = len -1; i >= 0; i--) {
        String last = s.substring(i, len);  //get the last word and process the rest
        if (dict.contains(last)) {
            if (i == 0) {
                words.add(last);
            } else {
                String remain = s.substring(0, i);
                List<String> remainSet = wordBreak(remain, dict);
                if (remainSet != null) {
                    for (String item : remainSet) {
                        words.add(item + " " + last);
                    }
                }
            }
        }
    }
    return words;
}

如果我尝试从前面处理,结果应该相同。

public static List<String> wordBreakFront(String s, Set<String> dict) {
    List<String> words = new ArrayList<String>();

    int len = s.length();
    for (int i = 1; i <= len; i++) {
        String front = s.substring(0, i);
        if (dict.contains(front)) {
            if (i == len) {
                words.add(front);
            } else {
                //get the front word and process the rest.  
                String remain = s.substring(i, len);
                List<String> remainSet = wordBreak(remain, dict);
                if (remainSet != null) {
                    for (String item : remainSet) {
                        words.add(front + " " + item);
                    }
                }
            }
        }
    }
    return words;
}

前跟踪也有效(可以生成正确的输出)。但它效率低,然后在时间限制测试中失败。后来在这种情况下失败了:

//最后执行输入: “aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab”,[ “一”, “AA”, “AAA”, “AAAA”, “AAAAA”, “AAAAAA”, “AAAAAAA”, “AAAAAAAA”, “AAAAAAAAA”, “AAAAAAAAAA”]

所以我不明白为什么从后面开始会有所作为?

感谢。

1 个答案:

答案 0 :(得分:2)

在最坏的情况下,它们都具有指数时间复杂度。幸运的是,第一个通过了,第二个通过了(如果你反转输入的单词和字典中的所有单词,第一个单词的工作时间太长了。)