题注
这道题本身不难,不过这次涉及到一些数学分析,很基础。LeetCode的题目本身都比较基础,但是正如《灌篮高手》里面赤木刚宪对樱木花道说的:基础最重要。没有掌握好的代码基础,剩下的一切都是扯淡。
题目
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
补充知识:Binary Search Trees
A binary search tree (BST), sometimes also called anordered orsorted binary tree, is a node-based binary data structure which has the following properties:
- 1. The left subtree of a node contains only nodes with keys less than the node's key.
- 2. The right subtree of a node contains only nodes with keys greater than the node's key.
- 3. The left and right subtree each must also be a binary search tree.
- 4. There must be no duplicate nodes.
分析
Binary Search Tree的最大特点是节点左子树所有节点值小于节点值本身;又子树所有节点值大于节点值本身。Binary Search Tree也有递归特性,因此自然而然地,这道题用递归特性(更确切的说,分治方法)来做最为合适。
如何递归呢?我们设函数$numTrees(n)$为存储了$[1, n]$的树中,Binary Search Tree的数量。显然地,我们有:
\[numTrees(0) = 0\]
\[numTrees(1) = 1\]
当$n \geq 2$时,我们分别将root节点的值设为$1,2, \cdots n$。当root节点值为$i \in [1, n]$时,其左子树的值必然为全部的$[1, i - 1]$(由性质1所确定),其右子树的值必然为全部的$[i+1, n]$(由性质2所确定)。同时,左右子树又必然为Binary Search Tree(由性质3所决定)。因此,左子树便成为了一个numTrees(i - 1)问题,右子树便称为了一个numTrees(n - 1 - i)问题。形式化的说,我们有,对于所有的$n \geq 2$:
\[numTrees(n) = numTrees(0) \cdot numTrees(n-1) + numTrees(1) \cdot numTrees(n-2) + \cdots + numTrees(n-1) \codt numTrees(0)\]
问题就迎刃而解了。
不过,为了简单地递归,我们这里设为$numTrees(0) = 1$,这样$numTrees(0) \cdot numTrees(n-1)$便不为$0$了,方便进行处理。
代码
public class Solution {
public int reverse(int x) {
boolean isNeg;
if (x < 0){
isNeg = true;
x = -1 * x;
}else{
isNeg = false;
}
int reverResult = 0;
while (x != 0){
reverResult = reverResult * 10 + x % 10;
x = x / 10;
}
if (isNeg){
reverResult = -1 * reverResult;
}
return reverResult;
}
}