(1) Recover Binary Search Tree
这题的要点就是想到使用树的递归中序遍历,因为二叉查找树合法的情况,中序遍历的值是从小到大排列的。
当出现当前值比前一个值小的时候,就是存在不合法的节点。
用pre存中序遍历时当前节点的前一个节点,方便值的大小对比,用big,small记录这两个不合法序列的位置,big存较大的值,small存较小的值。
最后把两个不合法的值交换。[1]
class Solution {
private:
TreeNode *big,*small,*pre;
void solve(TreeNode *root) {
if(!root)
return;
solve(root->left);
if(pre && pre->val > root->val)
{
if(!big)
{
big=pre;
small=root;
}
else
small=root;
}
pre=root;
solve(root->right);
}
public:
void recoverTree(TreeNode *root) {
if(!root)
return;
big=small=pre=NULL;
solve(root);
swap(big->val,small->val);
}
};
百度之,发现正确的解出来方法是用二维的dp。
假如我们要将字符串str1变成str2
sstr1(i)是str1的子串,范围[0到i),sstr1(0)是空串
sstr2(j)是str2的子串,同上
d(i,j)表示将sstr1(i)变成sstr2(j)的编辑距离
首先d(0,t),0<=t<=str1.size()和d(k,0)是很显然的。
当我们要计算d(i,j)时,即计算sstr1(i)到sstr2(j)之间的编辑距离,
此时,设sstr1(i)形式是somestr1c;sstr2(i)形如somestr2d的话,
将somestr1变成somestr2的编辑距离已知是d(i-1,j-1)
将somestr1c变成somestr2的编辑距离已知是d(i,j-1)
将somestr1变成somestr2d的编辑距离已知是d(i-1,j)
那么利用这三个变量,就可以递推出d(i,j)了:
如果c==d,显然编辑距离和d(i-1,j-1)是一样的
如果c!=d,情况稍微复杂一点:
如果将c替换成d,编辑距离是somestr1变成somestr2的编辑距离 + 1,也就是d(i-1,j-1) + 1
如果在c后面添加一个字d,编辑距离就应该是somestr1c变成somestr2的编辑距离 + 1,也就是d(i,j-1) + 1
如果将c删除了,那就是要将somestr1编辑成somestr2d,距离就是d(i-1,j) + 1
那最后只需要看着三种谁最小,就采用对应的编辑方案了。
递推公式出来了,程序也就出来了。[2]
class Solution {
public:
int minDistance(string word1, string word2) {
if(word1.size()==0)
return word2.size();
else if(word2.size()==0)
return word1.size();
int dp[word1.size()+1][word2.size()+1];
for(int i=0;i<=word1.size();i++)
dp[i][0]=i;
for(int j=0;j<=word2.size();j++)
dp[0][j]=j;
for(int i=1;i<=word1.size();i++)
for(int j=1;j<=word2.size();j++)
{
if(word1[i-1]==word2[j-1])
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=min(min(dp[i-1][j-1]+1,dp[i][j-1]+1),dp[i-1][j]+1);
}
return dp[word1.size()][word2.size()];
}
};
(3) Reverse Nodes in k-Group
方法比较耿直,每K个一组来reverse:
class Solution {
private:
ListNode* reverseAGroup(ListNode *start,int k)
{
ListNode *pre,*cur,*ret;
pre=start->next;
cur=pre->next;
ret=pre;
for(int i=0;i<k-1;i++)
{
ListNode *tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
start->next->next=cur;
start->next=pre;
return ret;
}
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(!head)
return NULL;
if(k==1)
return head;
ListNode begin(0);
ListNode *cur,*start;
int flag=0;
begin.next=head;
cur=&begin;
while(cur->next){
start=cur;
for(int i=0;i<k;i++)
{
cur=cur->next;
if(!cur)
{
flag=1;
break;
}
}
if(flag==1)
break;
else
cur=reverseAGroup(start,k);
}
return begin.next;
}
};
参考:
[1] http://blog.csdn.net/havenoidea/article/details/12869021
[2] http://blog.unieagle.net/2012/09/19/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Aedit-distance%EF%BC%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%8B%E9%97%B4%E7%9A%84%E7%BC%96%E8%BE%91%E8%B7%9D%E7%A6%BB%EF%BC%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/