LeetCode-Unique Binary Search Trees
同上一道返回bst树的题目的思路,
求数目的话更加简单;
1 class Solution { 2 public: 3 int numTrees(int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (n <= 0) { 7 return 0; 8 } 9 int count = 0; 10 getNum(count, 1, n + 1); 11 return count; 12 } 13 void getNum(int &count, int l, int r) { 14 if (l == r) { 15 count = 1; 16 return; 17 } 18 for (int i = l; i < r; ++i) { 19 int left = 0; 20 getNum(left, l, i); 21 int right = 0; 22 getNum(right, i + 1, r); 23 count += left * right; 24 } 25 } 26 };