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.
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;
}
};
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;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解