您的位置:首页 > 编程语言 > C语言/C++

leetcode #96 in cpp

2016-06-15 11:10 260 查看
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


Solution:

Similar to #95. 

Code:

class Solution {
public:
int numTrees(int n) {
vector<vector<int>> dp(n,vector<int>(n,-1));
return calNum(1,n,dp);
}
int calNum(int start, int end, vector<vector<int>> &dp){
int res = 0;
if(start > end) return 1;
if(dp[start-1][end-1] != -1) return dp[start-1][end-1];
for(int rootval = start; rootval <= end; rootval++){
int left = calNum(start, rootval-1,dp);
int right = calNum(rootval+1, end,dp);
res +=left*right;
}
dp[start-1][end-1] = res;
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode