Leetcode 96: 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
Note : two solutions 1. dfs + memorization 2. dp. We should learn that problems that can be solved in a top - down direction (DFS) we can also usually solve in bottom-up way (DP).
1 public int NumTrees(int n) { 2 var dp = new int[n + 1]; 3 dp[0] = 1; 4 dp[1] = 1; 5 6 for (int nodes = 2; nodes <= n; nodes++) 7 { 8 for (int i = 1; i <= nodes; i++) 9 { 10 dp[nodes] += dp[i - 1] * dp[nodes - i]; 11 } 12 } 13 14 return dp[n]; 15 }
1 public class Solution { 2 private Dictionary<int, int> cache = new Dictionary<int, int>(); 3 public int NumTrees(int n) { 4 return DFS(1, n); 5 } 6 7 private int DFS(int start, int end) 8 { 9 if (start >= end) return 1; 10 if (start + 1 == end) return 2; 11 12 if (cache.ContainsKey(end - start)) return cache[end - start]; 13 14 var result = 0; 15 for (int i = start; i <= end; i++) 16 { 17 result += DFS(start, i - 1) * DFS(i + 1, end); 18 } 19 20 cache[end - start] = result; 21 22 return result; 23 } 24 }