LeetCode_96Unique Binary Search Trees

来源:互联网 发布:结构优化设计公司 编辑:程序博客网 时间:2024/05/01 11:38

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

由于当节点数增加时,当前的结果会依赖前面的结果所以考虑用动态规划。

  • 当节点数为0时,dp[0]=1;
  • 当节点数为1时,结果也唯一,dp[1]=1;
  • 当节点数为2时,可能结果为两个,也即dp[0]*dp[1]+dp[1]*dp[0]
  • 当节点数为3时,可能节点数即为dp[0]*dp[2]+dp[1]*dp[1]+dp[2]*dp[0]

以i为根节点时,其左子树构成为[0,…,i-1],其右子树构成为[i+1,…,n]构成
因此,dp[i] = sum(dp[0…k] * dp[k+1…i]) 0 <= k < i - 1

     public int numTrees(int n) {         int dp[] = new int[n+1];         dp[0] = 1;         dp[1] = 1;         for(int i = 2;i <=n;i++){             dp[i] = 0;             for(int j = 0;j<i;j++){                 dp[i] += dp[j]*dp[i-j-1];             }         }           return dp[n];         }
0 0
原创粉丝点击