本文主要是介绍Unique Binary Search Trees问题及解法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
示例:
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问题分析:
根据题意分析可得,该题是一类动态规划问题,dp为状态转移数组, 状态转移公式为dp[n] += dp[i - 1] * dp[i - k] , 1 <= i <=n, 1 <=k <= i.
过程详见代码:
class Solution {
public:int numTrees(int n) {vector<int> dp(n + 1, 0);dp[0] = 1;dp[1] = 1;dp[2] = 2;for (int j = 3; j <= n; j++){for (int i = 0; i < j / 2; i++){dp[j] += 2 * dp[i] * dp[j - 1 - i];}if (j % 2) dp[j] += dp[j / 2] * dp[j / 2];}return dp[n];}
};
这篇关于Unique Binary Search Trees问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!