96. Unique Binary Search Trees LeetCode
2016-02-13 18:24
537 查看
题意:求n个节点能生成不同搜索二叉树的方案数。
题解:dp,dp[i] 表示有i个节点的时候能生成不同的搜索二叉树的方案数。那么转移等于dp[i] = dp[j - 1] * dp[i - j] (1<= j <= i).也就是左边j - 1个节点,右边 i - j个节点。
题解:dp,dp[i] 表示有i个节点的时候能生成不同的搜索二叉树的方案数。那么转移等于dp[i] = dp[j - 1] * dp[i - j] (1<= j <= i).也就是左边j - 1个节点,右边 i - j个节点。
class Solution { public: int numTrees(int n) { int dp[n + 1]; memset(dp,0,sizeof(dp)); dp[0] = dp[1] = 1; dp[2] = 2; for(int i = 3; i <= n; i++) { for(int j = 1; j <= i; j++) { dp[i] += dp[j - 1] * dp[i - j]; } } return dp ; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 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
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解