先保存一下 某个大神的DP专辑:http://www.cnblogs.com/remlostime/tag/DP/
1. 还是用DP啊,尼玛还是码不出来 TTTTTTT。。。。。dp[i][j]表示s1[0~i]&s2[0~j]组成的串串,是否能组成s3[0,i+j]。
2,递归 + 剪枝,前后同时判断。
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
, return true.
When s3 = "aadbbbaccc"
, return false.
1,DP
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length();
int len2 = s2.length();
int len3 = s3.length();
if (len1 + len2 != len3) {
return false;
}
boolean[][] dp = new boolean[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
if (s1.substring(0, i).equals(s3.substring(0, i))) {
dp[i][0] = true;
} else {
break;
}
}
for (int i = 0; i <= len2; i++) {
if (s2.substring(0, i).equals(s3.substring(0, i))) {
dp[0][i] = true;
} else {
break;
}
}
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (s3.charAt(i + j -1) == s1.charAt(i - 1) && s3.charAt(i + j -1) == s2.charAt(j - 1)) {
dp[i][j] = (dp[i-1][j] || dp[i][j-1]);
} else if (s3.charAt(i + j -1) == s1.charAt(i - 1)) {
dp[i][j] = dp[i-1][j];
} else if (s3.charAt(i + j -1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i][j-1];
}
}
}
return dp[len1][len2];
}
}
2. Recursion
public class Solution {
String str1;
String str2;
String str3;
public boolean isInterleave(String s1, String s2, String s3) {
if (s3.length() != s1.length() + s2.length()) return false;
str1 = s1;
str2 = s2;
str3 = s3;
return helper(0, s1.length()-1, 0, s2.length()-1, 0, s3.length()-1);
}
public boolean helper(int p1, int q1, int p2, int q2, int p3, int q3) {
if (p3 > q3) return true;
if (p1 > q1 || p2 > q2) {
if (p2 <= q2) {
while (p2 <= q2 && str2.charAt(p2) == str3.charAt(p3)) {
p3++;
p2++;
}
}
if (p1 <= q1) {
while (p1 <= q1 && str1.charAt(p1) == str3.charAt(p3)) {
p3++;
p1++;
}
}
if (p3 <= q3) return false;
return true;
}
if (str1.charAt(p1) == str3.charAt(p3)) {
if (str1.charAt(q1) == str3.charAt(q3)
&& helper(p1+1, q1-1, p2, q2, p3+1, q3-1)) {
return true;
}
if (str2.charAt(q2) == str3.charAt(q3)
&& helper(p1+1, q1, p2, q2-1, p3+1, q3-1)) {
return true;
}
}
if (str2.charAt(p2) == str3.charAt(p3)) {
if (str1.charAt(q1) == str3.charAt(q3)
&& helper(p1, q1-1, p2+1, q2, p3+1, q3-1)) {
return true;
}
if (str2.charAt(q2) == str3.charAt(q3)
&& helper(p1, q1, p2+1, q2-1, p3+1, q3-1)) {
return true;
}
}
return false;
}
}