图解DFS求解Word Break II -- LeetCode
来源:互联网 发布:adobe flash cc mac版 编辑:程序博客网 时间:2024/06/18 13:13
Given a string s and a dictionary of wordsdict, add spaces in s to construct a sentence where each word is a validdictionary 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"].
Code_Ganker在求解过程中采用了DFS方法进行暴力求解,总共找到了两组结果分别为[cat, sand, dog]和[cats, and, dog],具体的图解如下所示。
下面对上图进行简单的分析,具体的细节,大家自己调试一下就清楚了。
1.首先向helper方法中传入字符串catsanddog,字典["cat","cats", "and", "sand", "dog"],开始查找位置0,接收结果的集合res
2.helper方法开始遍历整个字符串,从i = 0开始,用stringbuilder接收截取的字符串,当i = 2时,str中截取的子串为cat,字典中含有该子串,添加到item中。
3.调用helper,此时i = 3开始查找,找到了sand,字典比对后发现存在,添加到item中,此时item = {cat sand}。
4.继续调用helper,此时i = 7开始查找,找到了sand,字典比对后发现存在,添加到item中,此时item = {cat sand dog}。
5.继续调用helper,此时i = 10,超过了字符串长度9,符合终止条件,将item添加到res中。
6.向上回溯到i = 9,此时程序结束,继续回溯到i = 7,i++,查找是否有子串在字典中,没找到,回溯到i = 3,i++,在cat基础上继续添加s编程cats。
7.转换到了树的另外一个分支,cats在字典中存在,添加到item中。
8.继续调用helper向下搜索,此时i = 4,从i = 4开始截取当i = 6时,截取了子串and。and在字典中,添加到item中,此时item = [cats and]。
9.继续调用helper向下搜索,此时i = 7,从i = 7开始截取当i = 9时,截取了子串dog。dog在字典中,添加到item中,此时item = [cats and dog]
10.继续调用helper,此时i = 10,超过了字符串长度9,符合终止条件,将item添加到res中。此时res中有两个结果。
11.向上回溯到i = 9,此时程序结束,继续回溯到i = 7,i++,查找是否有子串在字典中,没找到,回溯到i = 3,i++,没找到,将res返回main函数。
这道题的思路我的理解就是这样的,如果有不对的地方,希望大家能够批评指正。通过图解分析思路容易理解,希望大家共同进步!
- 图解DFS求解Word Break II -- LeetCode
- Leetcode dfs Word Break II
- LeetCode 140. Word Break II (DP+DFS)
- LeetCode Word Break II DP+DFS
- LeetCode Word Break(DFS)
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- Leetcode--Word Break II
- Mybatis查询语句返回对象和泛型集合
- echarts往ssh项目中引入
- 根据《LINUX就该这么学》总结的常用命令
- jms消息服务使用
- PhpStorm激活
- 图解DFS求解Word Break II -- LeetCode
- 3.3 Linux获取系统信息(1、2节)
- TensorFlow 用 tf.nn.max_pool 实现最大池化操作
- GeoTools Eclipse 快速入门01
- 登录界面跳转,同时将onpause();方法中的保存的数据传到第二个页面
- nodejs的优缺点及适用场景
- Dagger2-android (不是dagger2)使用
- 什么是Schema
- ACM_03复习高中知识