LeetCode里有特色的问题存档

002* Median of Two Sorted Arrays

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

 1 class Solution:
 2     def findKth(self, A, A_start, B, B_start, k):
 3         if A_start >= len(A):
 4             return B[B_start + k - 1]
 5         if B_start >= len(B):
 6             return A[A_start + k - 1]
 7         if k == 1:
 8             return min(A[A_start], B[B_start])
 9         A_key = 0x3f3f3f3f
10         if A_start + k / 2 - 1 < len(A):
11             A_key = A[A_start + k / 2 - 1]
12         B_key = 0x3f3f3f3f
13         if B_start + k / 2 - 1 < len(B):
14             B_key = B[B_start + k / 2 - 1]
15         if A_key < B_key:
16             return self.findKth(A, A_start + k / 2, B, B_start, k - k / 2)
17         else:
18             return self.findKth(A, A_start, B, B_start + k / 2, k - k / 2)
19     # @return a float
20     def findMedianSortedArrays(self, A, B):
21         n = len(A) + len(B)
22         if n % 2 == 0:
23             return (self.findKth(A, 0, B, 0, n / 2) + self.findKth(A, 0, B, 0, n / 2 + 1)) / 2.0
24         else:
25             return self.findKth(A, 0, B, 0, n / 2 + 1)
View Code

出自算法导论9.3-8,设X[1..n]和Y[1..n]为两个数组,每个都包含n个已排好序的数。给出一个求数组X和Y中所有2n个元素的中位数的、O(lgn)时间算法。

 1 int findMedian(int A[],int B[],int n,int low,int high) {  
 2     if (low > high) return NOT_FOUND;  
 3     else {  
 4         int k = (low+high)/2;  
 5         if (k==n && A[n]<=B[1]) return A[n];  
 6         else if (k<n && B[n-k]<=A[k] && A[k]<=B[n-k+1]) return A[k];  
 7         else if (A[k] > B[n-k+1]) return findMedian(A,B,n,low,k-1);  
 8         else return findMedian(A,B,n,k+1,high);  
 9     }  
10 }  
11 int twoArrayMedian(int X[],int Y[],int n) {  
12     int median = findMedian(X,Y,n,1,n);  
13     if (median==NOT_FOUND) median = findMedian(Y,X,n,1,n);  
14     return median;  
15 }  
View Code

我们要取下中位数,注意到一个数x是中位数,当且仅当有n-1个数比x小,有n个数比x大,我们首先假设中位数在数组A中,二分中位数可能在的位置。
假设中位数所在区间为[L,R],k为(L+R)/2。若A[k]是中位数,数组A中有k-1个数比A[k]小,n-k个数比A[k]大。若B中有n-k个数比A[k]小,有k个数比A[k]大,则A[k]是中位数。
由于B是已排序的,因此B[n-k]<=A[k]<=B[n-k+1]。
若A[k]>B[n-k+1],则比A[k]小的数至少有n个,所以中位数小于A[k],因此在区间[L,k-1]中。
反之则在区间[k+1,R]中。
若L>R,则中位数不在A中,对B数组进行同样的二分操作即可。

010* Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
 1 class Solution {
 2 public:
 3     bool isMatch(const char *s, const char *p) {
 4         if (*p == 0) return *s == 0;
 5         if (*(p + 1) != '*') {
 6             if (*s != 0 && (*p == *s || *p == '.')) return isMatch(s + 1, p + 1);
 7             else return false;
 8         }
 9         else {
10             while (*s != 0 && (*s == *p || *p == '.')) {
11                 if (isMatch(s, p + 2)) return true;
12                 s++;
13             }
14             return (isMatch(s, p + 2));
15         }
16     }
17 };
View Code

显然暴搜就可以了,但是同样的方法python却超时了。所以python有风险,提交需谨慎。

011* Container With Most Water  

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

 1 class Solution:
 2     # @return an integer
 3     def maxArea(self, height):
 4         n = len(height)
 5         L = 0
 6         R = n - 1
 7         ans = 0
 8         while L < R:
 9             tmp = (R - L) * min(height[L], height[R])
10             if tmp > ans:
11                 ans = tmp
12             if height[L] < height[R]:
13                 b = height[L]
14                 while L < n and height[L] <= b:
15                     L += 1
16             else:
17                 b = height[R]
18                 while R >= 0 and height[R] <= b:
19                     R -= 1
20         return ans
View Code

关键在于如果已经计算过[L,R],如果h[L+1....]<h[L],那肯定不更优,同理如果h[R-1....]<h[R],那肯定不是更优解。

所以要找h[L']>h[L]以及h[R']>h[R]。

012* Integer to Roman   

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

 1 class Solution:
 2     # @return a string
 3     def intToRoman(self, num):
 4         s = ""
 5         if num >= 1000:
 6             i = num / 1000
 7             for j in range(i):
 8                 s = s + "M"
 9             num -= 1000 * i
10         if num >= 900:
11             s = s + "CM"
12             num -= 900
13         if num >= 500:
14             s = s + "D"
15             num -= 500
16         if num >= 400:
17             s = s + "CD"
18             num -= 400
19         if num >= 100:
20             i = num / 100
21             for j in range(i):
22                 s = s + "C"
23             num -= 100 * i
24         if num >= 90:
25             s = s + "XC"
26             num -= 90
27         if num >= 50:
28             s = s + "L"
29             num -= 50
30         if num >= 40:
31             s = s + "XL"
32             num -= 40
33         if num >= 10:
34             i = num / 10
35             for j in range(i):
36                 s = s + "X"
37             num -= 10 * i
38         if num >= 9:
39             s = s + "IX"
40             num -= 9
41         if num >= 5:
42             s = s + "V"
43             num -= 5
44         if num >= 4:
45             s = s + "IV"
46             num -= 4
47         for j in range(num):
48             s = s + "I"
49         return s
View Code

问题在于我根本不知道罗马字母什么原理。。。

013* Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 1 class Solution:
 2     # @return an integer
 3     def romanToInt(self, s):
 4         n = len(s)
 5         p = 0
 6         num = 0
 7         cnt = 0
 8         while p < n:
 9             if s[p] == 'M':
10                 cnt = 0
11                 while p < n and s[p] == 'M':
12                     cnt += 1
13                     p += 1
14                 num += 1000 * cnt
15             elif p + 1 < n and s[p:p+2] == 'CM':
16                 num += 900
17                 p += 2
18             elif s[p] == 'D':
19                 num += 500
20                 p += 1
21             elif p + 1 < n and s[p:p+2] == 'CD':
22                 num += 400
23                 p += 2
24             elif s[p] == 'C':
25                 cnt = 0
26                 while p < n and s[p] == 'C':
27                     cnt += 1
28                     p += 1
29                 num += 100 * cnt
30             elif p + 1 < n and s[p:p+2] == 'XC':
31                 num += 90
32                 p += 2
33             elif s[p] == 'L':
34                 num += 50
35                 p += 1
36             elif p + 1 < n and s[p:p+2] == 'XL':
37                 num += 40
38                 p += 2
39             elif s[p] == 'X':
40                 cnt = 0
41                 while p < n and s[p] == 'X':
42                     cnt += 1
43                     p += 1
44                 num += 10 * cnt
45             elif p + 1 < n and s[p:p+2] == 'IX':
46                 num += 9
47                 p += 2
48             elif s[p] == 'V':
49                 num += 5
50                 p += 1
51             elif p + 1 < n and s[p:p+2] == 'IV':
52                 num += 4
53                 p += 2
54             elif s[p] == 'I':
55                 cnt = 0
56                 while p < n and s[p] == 'I':
57                     cnt += 1
58                     p += 1
59                 num += cnt
60         return num
View Code

倒着搞一遍

016* 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int> &num, int target) {
 4         sort(num.begin(), num.end());
 5         int n = num.size();
 6         int ans = 0x3f3f3f3f;
 7         int res = 0;
 8         for (int p = 0; p < n; p++) {
 9             int L = 0;
10             int R = n - 1;
11             while (L < R) {
12                 if (L == p) {
13                     L++;
14                     continue;
15                 }
16                 if (R == p) {
17                     R--;
18                     continue;
19                 }
20                 int sum = num[L] + num[R] + num[p];
21                 if (abs(sum - target) < ans) {
22                     ans = abs(sum - target);
23                     res = sum;
24                 }
25                 if (sum < target) {
26                     L++;
27                 }
28                 else if (sum > target) {
29                     R--;
30                 }
31                 else {
32                     ans = 0;
33                     res = sum;
34                     break;
35                 }
36             }
37         }
38         return res;
39     }
40 };
View Code

python依然TLE,所以python有风险。。

枚举一个数,线性探查另外另个数。

017* 4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)
 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4         set<long long> st;
 5         sort(num.begin(), num.end());
 6         vector<vector<int> > res;
 7         int n = num.size();
 8         for (int i = 0; i < n; i++){
 9             for (int j = i + 1; j < n; j++) {
10                 int L = j + 1;
11                 int R = n - 1;
12                 while (L < R) {
13                     int sum = num[i] + num[j] + num[L] + num[R];
14                     if (sum < target) {
15                         while (L + 1 < R && num[L + 1] == num[L]) L++;
16                         L++;
17                     }
18                     else if (sum > target) {
19                         while (L < R - 1 && num[R - 1] == num[R]) R--;
20                         R--;
21                     }
22                     else {
23                         vector<int> v = { num[i], num[j], num[L], num[R] };
24                         res.push_back(v);
25                         while (L + 1 < R && num[L + 1] == num[L]) L++;
26                         L++;
27                         while (L < R - 1 && num[R - 1] == num[R]) R--;
28                         R--;
29                     }
30                 }
31                 while (j + 1 < n && num[j + 1] == num[j]) j++;
32             }
33             while (i + 1 < n && num[i + 1] == num[i]) i++;
34         }
35         return res;
36     }
37 };
View Code

同样是先枚举前两个数,然后线性找后两个数。多了一个判重。

018* Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

 1 class Solution:
 2     def gao(self, dep):
 3         if dep == self.n:
 4             s = ""
 5             for c in self.s:
 6                 s+=c
 7             self.ans.append(s)
 8             return
 9         idx = int(self.digits[dep])
10         for i in range(len(self.phone[idx])):   
11             self.s.append(self.phone[idx][i])
12             self.gao(dep+1)
13             self.s.pop()
14     # @return a list of strings, [s1, s2]
15     def letterCombinations(self, digits):
16         self.phone = ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
17         self.ans = []
18         self.n = len(digits)
19         self.s = []
20         self.digits = digits
21         self.gao(0)
22         return self.ans
View Code

021* Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

 1 class Solution:
 2     def gao(self, pl, pr):
 3         if pl == self.n and pr == self.n:
 4             gen = ""
 5             for c in self.gen:
 6                 gen+=c
 7             self.ans.append(gen)
 8             return
 9         if pl < self.n:
10             self.stack.append('(')
11             self.gen.append('(')
12             self.gao(pl + 1, pr)
13             self.gen.pop()
14             self.stack.pop()
15         if len(self.stack) > 0 and pr < self.n:
16             self.stack.pop()
17             self.gen.append(')')
18             self.gao(pl, pr + 1)
19             self.gen.pop()
20             self.stack.append('(')
21     # @param an integer
22     # @return a list of string
23     def generateParenthesis(self, n):
24         self.n = n
25         self.ans = []
26         self.stack = []
27         self.gen = []
28         self.gao(0, 0)
29         return self.ans
View Code

括号匹配,直接搜

023* Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

 1 class Solution:
 2     # @param a ListNode
 3     # @return a ListNode
 4     def swapPairs(self, head):
 5         cur = tmp = pre = None
 6         cur = head
 7         if cur != None and cur.next != None:
 8             head = cur.next
 9         while cur != None:
10             if cur.next == None:
11                 return head
12             next = cur.next
13             if pre != None:
14                 pre.next = next
15             tmp = next.next
16             next.next = cur
17             cur.next = tmp
18             pre = cur
19             cur = cur.next
20         return head
View Code

024* Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

 1 class Solution:
 2     def gao(self, head, k):
 3         cnt = 0
 4         p = head
 5         while p != None:
 6             p = p.next
 7             cnt += 1
 8         if cnt < k:
 9             return head, None
10         p = head
11         pre = p
12         next = None
13         tmp = None
14         while k > 1 and p.next != None:
15             tmp = next = p.next
16             p.next = next.next
17             next.next = pre
18             pre = tmp
19             k -= 1
20         head = pre
21         return head, p
22     # @param head, a ListNode
23     # @param k, an integer
24     # @return a ListNode
25     def reverseKGroup(self, head, k):
26         head, p = self.gao(head, k)
27         while p != None:
28             lst = p
29             p = p.next
30             tmp, p = self.gao(p, k)
31             lst.next = tmp
32         return head
View Code

为什么会有这么多链表操作题呢

029* Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

 1 class Solution:
 2     def check(self, p):
 3         #print "-------------------
", p
 4         L = R = p
 5         cnt = 0
 6         maxcnt = len(self.L)
 7         while L + self.len <= len(self.S) and R + self.len <= len(self.S):
 8             word = self.S[R:R+self.len]
 9             #print L,R,cnt,word
10             if self.dict.has_key(word) == False:
11                 L = R = R + self.len
12                 cnt = 0
13                 self.book = {}
14                 continue
15             if self.book.has_key(word) == False:
16                 self.book[word] = 0
17             self.book[word] += 1
18             cnt += 1
19             R += self.len
20             while self.book[word] > self.dict[word]:
21                 pre = self.S[L:L+self.len]
22                 self.book[pre] -= 1
23                 cnt -= 1
24                 L += self.len
25             if cnt == maxcnt:
26                 self.ans.append(L)
27 
28     # @param S, a string
29     # @param L, a list of string
30     # @return a list of integer
31     def findSubstring(self, S, L):
32         self.L = L
33         self.S = S
34         self.ans = []
35         self.dict = {}
36         self.len = len(L[0])
37         for c in L:
38             if self.dict.has_key(c) == False:
39                 self.dict[c] = 0
40             self.dict[c] += 1
41         for i in xrange(self.len):
42             self.book = {}
43             self.check(i)
44         return self.ans
View Code

 单词长度一致,尺取。

033* Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

 1 class Solution {
 2 public:
 3     int normalSearch(int A[], int L, int R, int target) {
 4         while (L<=R) {
 5             int mid=(L+R)/2;
 6             if (A[mid]==target) return mid;
 7             else if (A[mid]<target) L=mid+1;
 8             else R=mid-1;
 9         }
10         return -1;
11     }
12     int search(int A[], int n, int target) {
13         int L=0,R=n-1;
14         while (L<=R) {
15             int mid=(L+R)/2;
16             if (A[mid]==target) return mid;
17             if (L==mid) {
18                 L+=1;
19                 continue;
20             }
21             if (R==mid) {
22                 R-=1;
23                 continue;
24             }
25             if (A[mid]>A[L]) {
26                 if (A[L]<=target&&A[mid]>target) return normalSearch(A, L, mid-1, target);
27                 else L=mid+1;
28             }
29             else {
30                 if (A[R]>=target&&A[mid]<target) return normalSearch(A, mid+1, R, target);
31                 else R=mid-1;
32             } 
33         }
34         return -1;
35     }
36 };
View Code

046* Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

 1 class Solution {
 2 private:
 3     bool next(vector<int> &a, int n) {
 4         if (n==0||n==1) return false;
 5         for (int i=n-2;i>=0;i--) {
 6             if (a[i]<a[i+1]) {
 7                 for (int j=n-1;j>=0;j--) {
 8                     if (a[j]>a[i]) {
 9                         swap(a[i],a[j]);
10                         int L=i+1,R=n-1;
11                         while (L<R) {
12                             swap(a[L],a[R]);
13                             L++,R--;
14                         }
15                         return true;
16                     }
17                 }
18             }
19         }
20         return false;
21     }
22 public:
23     vector<vector<int> > permute(vector<int> &num) {
24         vector<vector<int> > ans;
25         sort(num.begin(),num.end());
26         ans.push_back(num);
27         while (next(num, num.size())) {
28             ans.push_back(num);
29         }
30         return ans;
31     }
32 };
View Code

084* Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.


Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].


The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int> &h) {
 4         int n = h.size();
 5         vector<int> f(n), g(n);
 6         for (int i=0;i<n;i++) {
 7             f[i]=i;
 8             g[i]=i;
 9         }
10         for (int i=0;i<n;i++) {
11             while (f[i]-1 >= 0 && h[f[i]-1] >= h[i]) {
12                 f[i]=f[f[i]-1];
13             }
14         }
15         for (int i=n-1;i>=0;i--) {
16             while (g[i]+1 < n && h[g[i]+1] >= h[i]) {
17                 g[i]=g[g[i]+1];
18             }
19         }
20         int ans = 0;
21         for (int i=0;i<n;i++) {
22             ans = max(ans, (g[i]-f[i]+1)*h[i]);
23         }
24         return ans;
25     }
26 };
View Code

091* Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         int n = s.length();
 5         if (n==0) return 0;
 6         vector<int> f(n+1);
 7         f[0]=1;
 8         if (s[0]=='0') f[1]=0;
 9         else f[1]=1;
10         for (int i=2;i<=n;i++) {
11             if (s[i-1]!='0') f[i]+=f[i-1];
12             if (s[i-2]=='1') f[i]+=f[i-2];
13             if (s[i-2]=='2'&&s[i-1]>='0'&&s[i-1]<='6') f[i]+=f[i-2];
14         }
15         return f[n];
16     }
17 };
View Code

092* Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 private:
11 public:
12     ListNode *reverseBetween(ListNode *head, int m, int n) {
13         if (head == NULL) return head;
14         ListNode *pp=head, *pprev=NULL;
15         for (int i=0;i<m-1;i++) {
16             pprev=pp;
17             pp=pp->next;
18         }
19         ListNode *prev=pp, *next=NULL, *p;
20         p=pp->next;
21         ListNode *last=pp;
22         for (int i=m;i<n;i++) {
23             next=p->next;
24             p->next = prev;
25             prev=p;
26             p=next;
27         }
28         last->next=p;
29         if (pprev) {
30             pprev->next=prev;
31         }
32         else {
33             head=prev;    
34         }
35         return head;
36         
37     }
38 };
View Code

097* Interleaving String

Given s1s2s3, 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 class Solution {
 2 public:
 3     bool isInterleave(string s1, string s2, string s3) {
 4         int n = s1.size();
 5         int m = s2.size();
 6         int len = s3.size();
 7         if (n==0&&m==0) {
 8             if (len==0) return true;
 9             else return false;
10         }
11         if (n==0) {
12             if (s2==s3) return true;
13             else return false;
14         }
15         if (m==0) {
16             if (s1==s3) return true;
17             else return false;
18         }
19         if (n+m!=len) return false;
20         vector<vector<bool> > f;
21         f.resize(n+1);
22         for (int i=0;i<=n;i++) {
23             f[i].resize(m+1);
24         }
25         f[0][0]=true;
26         for (int i=0;i<=n;i++) {
27             for (int j=0;j<=m;j++) {
28                 if (i>0 && s1[i-1]==s3[i+j-1] && f[i-1][j]) f[i][j]=true;
29                 if (j>0 && s2[j-1]==s3[i+j-1] && f[i][j-1]) f[i][j]=true;
30             }
31         }
32         if (f[n][m]) return true;
33         return false;
34     }
35 };
View Code

099* Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / 
 2   3
    /
   4
    
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 private:
12     TreeNode *mis1, *mis2, *pre;
13 public:
14     void dfs(TreeNode *root) {
15         if (root->left != NULL) dfs(root->left);
16         if (pre!=NULL && root->val < pre->val) {
17             if (mis1 == NULL) {
18                 mis1 = pre;
19                 mis2 = root;
20             }
21             else {
22                 mis2 = root;
23             }
24         }
25         pre = root;
26         if (root->right != NULL) dfs(root->right);
27     }
28     void recoverTree(TreeNode *root) {
29         if (root == NULL) return;
30         mis1 = mis2 = pre = NULL;
31         dfs(root);
32         if (mis1!=NULL && mis2!=NULL) {
33             int tmp = mis1->val;
34             mis1->val = mis2->val;
35             mis2->val = tmp;
36         }
37     }
38 };
View Code
原文地址:https://www.cnblogs.com/zinthos/p/4156212.html