LeetCode 140

  • 这道题主要是搜索剪枝,最开始的时候由于太久没有做题,所以连剪枝都没有意识到,但是最终自己并没有做出来,看了discuss区的答案后写出来的,代码如下:
class Solution {

    Map> memory = new HashMap<>();

    public List wordBreak(String s, List wordDict) {

        if (memory.containsKey(s)) {
            return memory.get(s);
        }

        List result = new ArrayList<>();
        if (s.length() == 0) {

            result.add("");
            return result;
        }

        for (String word : wordDict) {

            if (s.startsWith(word)) {

                List sublist = wordBreak(s.substring(word.length()), wordDict);

                for (String sub : sublist) {

                    result.add(word + (sub.equals("") ? "" : " ") + sub);
                }
            }
        }

        memory.put(s,result);
        return result;
    }

}
  • 根据这个思路自己改了个dp,但是超时,能力不足,无法解决,代码如下。
class Solution {

    public List wordBreak(String s, List wordDict) {

        int s_len = s.length();
        List[][] dp = new ArrayList[s_len][s_len];
        for (int i = 0; i < s_len; i++) {
            for (int j = 0; j < s_len; j++) {
                dp[i][j] = new ArrayList<>();
            }
        }

        for (int i = s_len - 1; i >= 0; i--) {

            for (int j = i; j < s_len; j++) {

                String tmpStr = s.substring(i, j + 1);
                for (String word : wordDict) {

                    if (tmpStr.startsWith(word) && i + word.length() <= j + 1) {

                        int tmp_len = i + word.length();
                        if (tmp_len == j + 1) {
                            dp[i][j].add(word);
                        } else {
                            for (String str : dp[tmp_len][j]) {
                                dp[i][j].add(word + " " + str);
                            }
                        }
                    }
                }
            }
        }
        return dp[0][s_len - 1];
    }
}

你可能感兴趣的:(LeetCode 140)