[关闭]
@Lin-- 2020-02-24T13:58:31.000000Z 字数 796 阅读 319

numTrees

Leetcode


题意为:输入一个正整数,输出有该数量结点的二叉搜索树的数量。
解题思路如下:从1到n,分别做root结点。对于根节点为1的情况,它只有右子树。
对于根节点为2的情况,它有1棵左子树和n-2个节点组成的右子树。。。以此类推。
得到:




那么可以发现其实计算项是对称的,可以以此稍微降低复杂度:
对于偶数:只需要计算一半的项,然后*2即可;对于奇数,除中间的数不*2之外,其余*2再相加即可。

  1. /*
  2. *File:numTrees.c:
  3. *Author:0HP
  4. *Date:20200222
  5. *Purpose:to solve the problem in Leetcode
  6. *https://leetcode.com/problems/unique-binary-search-trees/
  7. */
  8. #include<stdio.h>
  9. #include<stdlib.h>
  10. int numTrees(int n){
  11. if(n<3){return n;}
  12. int *a;
  13. a=(int*)malloc(sizeof(int)*(n+1));
  14. a[0]=1;a[1]=1;a[2]=2;
  15. for(int i=3;i<n+1;++i)
  16. {
  17. int half=i/2;
  18. a[i]=0;
  19. if(i%2==0)
  20. {
  21. for(int j=0;j<half;++j)
  22. {
  23. a[i]=a[i]+a[i-j-1]*a[j];
  24. }
  25. a[i]=a[i]<<1;
  26. }
  27. else
  28. {
  29. for(int j=0;j<half;++j)
  30. {
  31. a[i]=a[i]+a[i-j-1]*a[j];
  32. }
  33. a[i]=a[i]*2+a[half]*a[half];
  34. }
  35. }
  36. return a[n];
  37. }
  38. int main ()
  39. {
  40. printf("%d",numTrees(3));
  41. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注