leetcode第96题不同的二叉搜索树

99 阅读1分钟

题目 给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。 题目链接

我的JavaScript解法

/**
 * @param {number} n
 * @return {number}
 */
var numTrees = function(n) {
 let memo = [];
 for(let i = 0; i < n+1; i++) {
   memo[i] = new Array(n+1).fill(0);
 }
 return count(1, n, memo);
};

const count = (low, high, memo) => {
  if (low > high) return 1;
  if (memo[low][high] != 0)
    return memo[low][high];
  
  let result = 0;
  for (let root = low; root <= high; root++) {
    let leftCount = count(low, root - 1, memo);
    let rightCount = count(root + 1, high, memo);
    result += leftCount * rightCount;
  }
  memo[low][high] = result;
  return result;
}

解析: 递归 + 备忘录

  • 时间复杂度: O(nGn)O(nG_n)
  • 空间复杂度: O(n2)O(n^2)