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
一开始是想用递归解决,但看了标签是dp问题,就想了一下, 数目为k的bst,其每个 0 ~ k - 1都可以分成两个区间, 然后又可以生成bst, 所以k的bst种类数等于取k左侧与右侧可划分成bst的乘机的总和,额,有点绕口额,代码清晰一点, 看代码:
1 class Solution { 2 public: 3 int numTrees(int n) { 4 vector<int> ret; 5 if(n == 0) return 0; 6 ret.reserve(n + 1); 7 ret[0] = 1; 8 for(int i = 1; i <= n; ++i){ 9 if(i < 3){ 10 ret[i] = i; 11 continue; 12 } 13 for(int j = 0; j < i; ++j){ 14 ret[i] += ret[j] * ret[i - j - 1]; 15 } 16 } 17 return ret[n]; 18 } 19 };
时间: 2024-11-10 13:13:32