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
https://oj.leetcode.com/problems/unique-binary-search-trees/
思路:只求个数,dp。dp[i]表示i个节点unique BST的数目。
初始化:dp[0]=0;dp[1]=1;dp[2]=2; 注意dp[0],表示子树是null的情况,也是只有一种情况,所以dp[0] = 1;
i>3: dp[i] + =dp[k]*dp[i-1-k] k从0~i-1。 对于n个node的树,加和每个node作为root的种类。
public class Solution { public int numTrees(int n) { if (n < 2) return 1; int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; dp[2] = 2; for (int i = 3; i <= n; i++) { for (int j = 0; j < i; j++) { dp[i] += dp[j] * dp[i - j - 1]; } } return dp[n]; } public static void main(String[] args) { System.out.println(new Solution().numTrees(1)); System.out.println(new Solution().numTrees(2)); } }
第二遍记录:注意dp的数组大小为 n+1。