動態規劃多版本iteration+recursion練習:LeetCode 139. Word Break
阿新 • • 發佈:2019-01-07
LeetCode 139. Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2: Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
分析題意可以發現,最終的答案可以由多個不同的路徑走過來,但是題目要求返回的只是最終能不能,因此,我們只需要在每個點返回可以不可以這樣一個boolean就行,另外再用一個boolean陣列記錄是否已經走過此位置,完成優化。但是iteration在理論上是沒有進行優化的,就是全部都走完,只有一個剪枝優化就是可以提前返回,但是iteration在空間和語法上是有優化的,因為陣列可以bulk load,但是recursion需要不停的從硬碟上來回取資料。
//iteration版本
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>();
for (String ss : wordDict) {
set.add(ss);
}
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
if (set.contains(s.substring(i,j+1)) && dp[i]) {
if (j == s.length() - 1) return true;
dp[j+1] = true;
}
}
}
return false;
}
// recursion版本
public boolean wordBreak(String s, List<String> wordDict) {
HashSet<String> set = new HashSet<>();
for (String ss : wordDict) {
set.add(ss);
}
boolean[] dp = new boolean[s.length()];
return recursion(s, set, 0, dp);
}
private boolean recursion(String s, HashSet<String> set, int index, boolean[] dp) {
//base case
if (index == s.length()) return true;
if (dp[index] == true) return false;
//recursion
boolean b = false;
for (int i = s.length() - 1; i >= index; i--) {
if (set.contains(s.substring(index, i+1))) {
b = b || recursion(s, set, i+1, dp);
}
}
dp[index] = true;
return b;
}