算法学习之回溯法(leetcode 140. Word Break II)

来源:互联网 发布:奇爱博士 知乎 编辑:程序博客网 时间:2024/05/22 13:35

leetcode 140. Word Break II
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].

A solution is [“cats and dog”, “cat sand dog”].

解题思路
按照DFS来思路来思考
需要设计好一个好的核心函数至关重要。
最直接的思路应该是
返回值为最后的结果集合,两个参数为字符串s,字典wordDict,如下

List<String> myDFS(String s, Set<String> wordDict)

然而,经过测试发现超时,所以添加一个HashMap保留中间结果。
源代码如下

public class Solution {    //此函数的含义解释    //输入给定字符串s, 给定词典wordDict, 保存结果的HashMap    //返回值为s的所有分隔结果,为<分隔结果1,分隔结果2,...>    public List<String> myDFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>> result){        //如果已经计算过了,则直接返回结果,不用重新计算了        if(result.containsKey(s)){            return result.get(s);        }        //否则没有计算过,继续        //声明一个保存结果的变量        LinkedList<String> cur = new LinkedList<String>();        //如果此时s的长度为0        if(s.isEmpty()){            //这个地方为什么不直接返回cur呢,待会看下            //这边如果不添加"",这个责结果为空,所以前面匹配成功的就无法添加到结果中去了。            cur.add("");            return cur;        }        for(String word : wordDict){            //如果s是以word作为prefix的话,可以尝试一下            if(s.startsWith(word)){                List<String> temp = myDFS(s.substring(word.length()), wordDict, result);                for(String subTemp : temp){                    cur.add(word + (subTemp.isEmpty() ? "" : " " + subTemp));                }            }        }        result.put(s, cur);        return cur;    }    public List<String> wordBreak(String s, Set<String> wordDict) {        //用来保存<字符串,字符串所有的分割结果>        HashMap<String, LinkedList<String>> result = new HashMap<String, LinkedList<String>>();        return myDFS(s, wordDict, result);    }}
0 0
原创粉丝点击