标签:
Given n, how many structurally unique BST‘s (binarysearch 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
HideTags
#pragma once #include<queue> #include<iostream> using namespace std; int numTrees(int n) { int *a=new int[n+1]; for (int i = 0; i < n + 1; i++) a[i] = 0; a[0] = 0; a[1] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j < i; j++) a[i] += (a[j - 1] * a[i - j]);//掐头去尾后,2至i-1做根节点时的可能数 a[i] += 2 * a[i - 1];//a[0]=0不能与a[i]相乘后叠加,掐头去尾单独算 } return a[n]; } void main() { cout << numTrees(1) << endl; cout << numTrees(2) << endl; cout << numTrees(3) << endl; cout << numTrees(4) << endl; system("pause"); }
标签:
原文地址:http://blog.csdn.net/hgqqtql/article/details/43308187