标签:
题目:
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
思路:
1 public class Solution { 2 /* 3 The case for 3 elements example 4 Count[3] = Count[0]*Count[2] (1 as root) 5 + Count[1]*Count[1] (2 as root) 6 + Count[2]*Count[0] (3 as root) 7 8 Therefore, we can get the equation: 9 Count[i] = ∑ Count[0...k] * [ k+1....i] 0<=k<i-1 10 11 */ 12 public int numTrees(int n) { 13 int[] count = new int[n+2]; 14 count[0] = 1; 15 count[1] = 1; 16 17 for(int i=2; i<= n; i++){ 18 for(int j=0; j<i; j++){ 19 count[i] += count[j] * count[i - j - 1]; 20 } 21 } 22 return count[n]; 23 } 24 }
reference:
http://www.jiuzhang.com/solutions/unique-binary-search-trees/
http://bangbingsyb.blogspot.com/2014/11/leetcode-unique-binary-search-trees-i-ii.html
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4831875.html