Leetcode Unique Binary Search Trees 代码,本代码使用down-up方法,并打印了相关信息,使用c++,如下:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int numTrees(int n) {
//recode the right most path height with i
vector<int> right(n + 1);
for (int i = 0; i <= n; i ++) {
right[i] = 0;
}
vector<int> re(n + 1);
re[1] = 1;
right[0] = 1;
for (int i = 2; i <= n; i ++) {
cout<<"begin:"<<endl;
//variable "pre" recode the right[i - 1] for calculate right[i]
int pre = right[0];
for (int j = 1; j < i; j ++) {
re[i] = re[i] + right[j] * j;
int temp = pre;
for (int k = j; k < i; k ++) {
temp += right[k];
}
pre = right[j];
right[j] = temp;
cout<<"right height :"<<j<<" value "<<right[j]<<endl;
}
right[0] = re[i - 1];
cout<<"right height :"<<0<<" value "<<right[0]<<endl;
re[i] = re[i] + re[i - 1] * 2;
cout<<"result "<<i<<": "<<re[i]<<endl;
cout<<"end:"<<endl;
}
return re[n];
}
};
int main() {
Solution a = Solution();
int b = a.numTrees(5);
cout<<"result: "<<b<<endl;
}