class Solution {
public int numTrees(int n) {
if (n < 1) {
return 0;
}
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
}
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length(), len2 = s2.length();
if (s3.length() != len1 + len2) {
return false;
}
boolean[][] dp = new boolean[len1 + 1][len2 + 1];
dp[0][0] = true;
for (int i = 1; i <= len1; i++) {
if (s1.charAt(i - 1) == s3.charAt(i - 1)) {
dp[i][0] = true;
} else {
break;
}
}
for (int j = 1; j <= len2; j++) {
if (s2.charAt(j - 1) == s3.charAt(j - 1)) {
dp[0][j] = true;
} else {
break;
}
}
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (dp[i - 1][j] == true && s1.charAt(i - 1) == s3.charAt(i + j - 1)) {
dp[i][j] = true;
} else if (dp[i][j - 1] == true && s2.charAt(j - 1) == s3.charAt(i + j - 1)) {
dp[i][j] = true;
}
}
}
return dp[len1][len2];
}
}
class Solution {
long pre = Long.MIN_VALUE;
public boolean inOrder(TreeNode root) {
if (root == null) {
return true;
}
if (inOrder(root.left) == false) {
return false;
}
if (root.val > pre) {
pre = root.val;
} else {
return false;
}
if (inOrder(root.right) == false) {
return false;
}
return true;
}
public boolean isValidBST(TreeNode root) {
return inOrder(root);
}
}
class Solution {
TreeNode first, second;
TreeNode pre = new TreeNode(Integer.MIN_VALUE);
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
if (root.val < pre.val && first == null) {
first = pre;
}
if (root.val < pre.val && first != null) {
second = root;
}
pre = root;
inOrder(root.right);
}
public void recoverTree(TreeNode root) {
inOrder(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null || p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
网友评论