Unique Binary Search Trees [LEETCODE]
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
============================================================
Since its a binary tree, so a recursive solution is reasonable.
For a root i, its unique BST number is equal to its left child's unique BST number multiple its right child's unique BST number.
1 class Solution { 2 public: 3 int numTrees(int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 return numTrees(1,n); 6 } 7 int numTrees(int start, int end){ 8 //pick a root 9 if(start >= end){ 10 return 1; 11 } 12 int total = 0; 13 for(int i = start; i <= end; i++){ 14 total += numTrees(start, i-1) * numTrees(i+1, end); 15 } 16 return total; 17 18 } 19 };

浙公网安备 33010602011771号