leetcode算法题解(Java版)-16-动态规划(单词包含问题)
摘要:?碰到二叉樹的問題,差不多就是深搜、廣搜,遞歸那方面想想了,當然如果要考慮一下空間、時間,還需要進行剪枝和壓縮處理。這題比較簡單:判斷兩個樹是否相等,可以遞歸的判斷子樹是否相等,最后找到邊界條件就是是否都為空,都不為空時節點里面的值是否相等。
一、遞歸
題目描述
Given two binary trees, write a function to check if they are equal or not.?
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
思路
- 碰到二叉樹的問題,差不多就是深搜、廣搜,遞歸那方面想想了,當然如果要考慮一下空間、時間,還需要進行剪枝和壓縮處理。這題比較簡單:判斷兩個樹是否相等,可以遞歸的判斷子樹是否相等,最后找到邊界條件就是是否都為空,都不為空時節點里面的值是否相等。
代碼
/*** Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {if(p==null&&q==null){return true;}else if(p==null||q==null){return false;}else if(q.val!=p.val){return false;}else{return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);}} }二、動態規劃
題目描述
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.?
For example, given
s ="leetcode",
dict =["leet", "code"].?
Return true because"leetcode"can be segmented as"leet code".
思路
- dp的題目,寫了幾道了。核心無非就是確定dp數組和狀態轉移方程。這幾道題都有明顯的特點,那就是dp數組記錄的就是所求的答案,所以答案一般都是dp[s.length()]這種形式的。
- 有了上面的總結,再來看著道題目。要求一串字母是否可以由所給的字典中的單詞拼出來,要求返回布爾型。那好,也同時提示我們了dp數組就是記錄它的子串是否能滿足要求,類型是布爾型:dp[i]表示的是s[0,i-1]這個子串能否滿足要求。
- dp[i]=dp[j]&&s[j,i]是否在字典中(0<=j<=i-1)
代碼
import java.util.Set;public class Solution {public boolean wordBreak(String s, Set<String> dict) {if(s==null||s.length()==0||dict==null||dict.size()==0){return false;}boolean [] dp = new boolean [s.length()+2];dp[0] = true;for(int i=1;i<=s.length();i++){for(int j=i-1;j>=0;j--){//從尾部掃描單詞if(dp[j]==true&&dict.contains(s.substring(j,i))){dp[i]=true;break;}else{dp[i]=false;}}}return dp[s.length()];} }三、深搜
題目描述
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"].
思路
- 題目是上一道題的加強版,為了考察動態規劃。感覺有點復雜,沒想出來怎么在上一道的基礎上改進。
- 深搜可以解決問題!直接看代碼了
代碼
import java.util.ArrayList; import java.util.Set;public class Solution {public ArrayList<String> res = new ArrayList<>();public ArrayList<String> wordBreak(String s, Set<String> dict) {dfs(s,s.length(),dict,"");return res;}public void dfs(String s,int index,Set<String> dict,String temp){if(index==0){if(temp.length()>0){res.add(temp.substring(0,temp.length()-1));//如果寫成res.add(temp)則末尾會多一個空格,小細節}}for(int i=index-1;i>=0;i--){if(dict.contains(s.substring(i,index))){dfs(s,i,dict,s.substring(i,index)+" "+temp);}}} }原文鏈接
本文為云棲社區原創內容,未經允許不得轉載。
總結
以上是生活随笔為你收集整理的leetcode算法题解(Java版)-16-动态规划(单词包含问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NLP产品级系统设计模式
- 下一篇: 他在阿里的逆袭,只因为想做个“锤子”