[leetcode]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
算法思路:
简单一维DP。跟这道题比起来[leetcode]Unique Binary Search Trees II,弱爆了。
代码如下:
public class Solution { public int numTrees(int n) { if(n < 0) return 0; int[] hash = new int[n + 3]; hash[0] = hash[1] = 1; hash[2] = 2; for(int i = 3; i <= n; i++){ for(int j = 1; j <= i; j++){ hash[i] += hash[j -1] * hash[i - j]; } } return hash[n]; } }