标签:
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. 运用自底向上的求解思路,减少求解的次数
2. 如果求n,则先求 1,2,3,4,5......n-1
3. 也可以尝试自顶向下的求解,将每次求解结果存在数组中,再次需要该数值时,直接读取,减少重复计算
class Solution{ public: int numTrees(int n) { int *ptr = new int [n+1]; int temp; if (n == 0) return 0; *ptr = 1; for (int i = 1; i<n+1; i++) { if (i < 3) *(ptr + i) = i; else { for (int j = 0; j<i; j++) { *(ptr+i) += *(ptr+j) * *(ptr+i-j-1); } } } temp= *(ptr+n); delete []ptr; return temp; } };
标签:
原文地址:http://www.cnblogs.com/NeilZhang/p/5347667.html