Leetcode: Unique Binary Search Trees
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
- f(n) = \sum_{i=1}^n f(i-1) * f(n-i), f(0) = 1, f(1) = 1;
- This is nature for DP (see below).
- f(n) = (2n)!/n!*(n+1)!, called Catalan number
class Solution{ public: int numTrees(int n) { vector<int> num(n+1, 0); num[0] = 1; if (n > 0) num[1] = 1; for(int i = 2; i < n+1; i++) for(int j = 0; j < i; j++) { num[i] += num[j]*num[i-j-1]; } return num[n]; } };
解法二:递归来做,不过有很多重复计算
//from stanford public class Solution { public int numTrees(int numKeys) { if(numKeys <= 1) return 1; // there will be one value at the root, with whatever remains // on the left and right each forming their own subtrees. // Iterate through all the values that could be the root... int sum = 0; int left, right, root; for(root = 1; root <= numKeys; root++) { left = countTrees(root - 1); right = countTrees(numKeys - root); sum += left * right; } return sum; } }
1 Use DP to solve this question. For any node i between node 1 to node n, f(n) += f(i-1)*f(n-i). 2 3 int numTrees(int n) { 4 int num, *f = (int*)malloc((n+1)*sizeof(int)); 5 memset(f, 0, (n+1)*sizeof(int)); 6 7 f[0] = 1; 8 f[1] = 1; 9 10 for (int j = 2; j <= n; j++) { 11 for (int i = 1; i <= j; i++) { 12 f[j] += f[i-1]*f[j-i]; 13 } 14 } 15 16 num = f[n]; 17 free(f); 18 19 return num; 20 }