标签:
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.
思路:
我的代码:
public class Solution { public int numTrees(int n) { if(n <= 1) return 1 ; int count = 0 ; for(int i = 1 ; i <= n ; i++ ) { int left = numTrees( i - 1) ; int right = numTrees( n - i ) ; count += left * right ; } return count ; } }
别人代码:
public class Solution { public int numTrees(int n) { int[] count = new int[n+2]; count[0] = 1; count[1] = 1; for(int i=2; i<= n; i++){ for(int j=0; j<i; j++){ count[i] += count[j] * count[i - j - 1]; } } return count[n]; } }
学到之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4313275.html