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题目地址: https://oj.leetcode.com/problems/unique-binary-search-trees/
这道题用递归的解法,很简单...
代码:
class Solution {
public:
int numTrees(int n) {
if(n==0||n==1) return 1;
int num=0;
for(int i=1;i<=n;i++){
//返回左边子树的个数和右边子树的组合数
num+=numTrees(i-1)*numTrees(n-i);
}
return num;
}
};