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
1 class Solution { 2 public: 3 int numTrees(int n) { 4 int *bst = new int[n+1]; 5 for(int i = 0 ; i < n+1; ++i) 6 bst[i] = 0; 7 8 bst[0] = 1; 9 bst[1] = 1; 10 for(int i = 2; i <= n; ++i){ 11 for(int j = 0 ; j < i; ++j){ 12 bst[i] += bst[j] * bst[i-j-1]; 13 } 14 } 15 return bst[n]; 16 } 17 };
动态规划?