题目
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的思想。当n<=2的时候,可以直接得出结果。当n > 2的时候,根节点有n中情况,对于这n种情况,分别考虑左右子树的个数,然后相乘。最后将这n中情况相加。使用数组保存结果。public int numTrees(int n) { if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 2; } int [] num = new int[n + 1]; num[0] = 1; num[1] = 1; num[2] = 2; int i = 3; while (i <= n) { int len = i - 1; int k = i - 1; int sum = 0; while (k >= 0) { sum += num[k] * num[len - k]; k--; } num[i] = sum; i++; } return num[n]; }