【LeetCode】Word Break II 动态规划
来源:互联网 发布:淘宝手办预定 编辑:程序博客网 时间:2024/05/12 09:03
题目:Word Break
要求找到所有能够有字典中的词重组成目标串的结果
public class Solution { public static List<String> wordBreak(String s, Set<String> dict) { List<String> dp[] = new ArrayList[s.length()+1]; dp[0] = new ArrayList<String>(); for(int i=0; i<s.length(); i++){ //i是开始位置 if( dp[i] == null ) continue; //前面的部分必须是可以匹配的 for(String word:dict){ int len = word.length(); int end = i+len; if(end > s.length()) continue; if(s.substring(i,end).equals(word)){ if(dp[end] == null){ dp[end] = new ArrayList<String>(); } dp[end].add(word);//记录上一个位置 } } } List<String> ans = new LinkedList<String>(); if(dp[s.length()] == null) return ans; ArrayList<String> tmp = new ArrayList<String>(); dfsStringList(dp,s.length(),ans, tmp); return ans; } public static void dfsStringList(List<String> dp[],int end,List<String> res, ArrayList<String> tmp){ if(end <= 0){ String ans = tmp.get(tmp.size()-1); for(int i=tmp.size()-2; i>=0; i--) ans += (" " + tmp.get(i) ); res.add(ans); return; } for(String str:dp[end]){ tmp.add(str); dfsStringList(dp,end-str.length(), res, tmp); tmp.remove(tmp.size()-1); } }}
0 0
- 【LeetCode】Word Break II 动态规划
- [LeetCode] [动态规划] Word Break
- 【LeetCode】Word Break 动态规划
- Word Break II[动态规划&DFS]
- 动态规划、递归:word-break II
- LeetCode练习-动态规划算法-word-break
- leetcode 140. Word Break II 动态规划DP + DFS深度优先搜索
- '动态规划:word-break'
- 动态规划:word-break
- [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
- mysql 安装问题 access denied for user 'root'@'localhost' using password yes/no
- 有序数组和二分法查找
- final 、finally和finalize有什么区别?
- hdu 1242 Rescue
- POJ - 3673 Cow Multiplication
- 【LeetCode】Word Break II 动态规划
- 初级官方卡刷包精简 添加万能ROOT
- apk 静默安装
- 一行代码比较用户A和用户B的年龄大小(两个日期计算)
- HDU 3787 A+B
- NOJ 2033 一页书的书 (组合数+dp)
- android博客
- 浅析人脸检测之Haar分类器方法
- 【SICP练习】132 练习3.63