算法总结

42 阅读1分钟

对称二叉树

// 给你一个二叉树的i根节点 root , 检查它是否轴对称。
const isSymmetric = function (root) {
  const left = root.left
  const right = root.right
  return isCorrect(left, right)
}

function isCorrect(left, right) {
  if (!left && !right) {
    return true
  }
  if (!left || !right) {
    return false
  }

  return left.val === right.val && isCorrect(left.left, right.right) && isCorrect(left.right, right.left)
}

柱状图中的最大矩形

var largestRectangleArea = function (heights) {
    let max = 0
    
    //初始化单调栈,存入索引和高度
    let stack = [{ index: -1, height: -1 }] 
    
    //遍历数组元素,依次入栈出栈
    for (let i = 0; i < heights.length; i++) {
    
        //当栈顶索引不为-1 并且 入栈元素高度小于栈顶元素高度,删除栈顶元素
        while (stack[stack.length - 1].index != -1 && stack[stack.length - 1].height > heights[i]) {
            let pop = stack.pop()
            
            //计算以出栈元素的height为高的矩形的最大面积,赋值给max
            max = Math.max(max, pop.height * (i - 1 - stack[stack.length - 1].index))
        }
        
        //确定高度大于栈顶元素后,元素入栈,存入索引和高度
        stack.push({ index: i, height: heights[i] })
    }
    
    //循环结束后,单调递增栈的元素的宽度均为栈顶的索引-各元素的索引
    let right = stack[stack.length - 1].index
    
    //当遍历结束,栈不为空时,将剩下元素依次出栈并计算面积
    while (stack[stack.length - 1].index != -1) {
        let pop = stack.pop()
        
        //求栈内剩下柱子的面积,赋值给max
        max = Math.max(max, (right  - stack[stack.length - 1].index) * pop.height)
    }

    return max
};
  

组合总数

// 给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,
// 找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,
// 并以列表形式返回。你可以按 任意顺序 返回这些组合。

// candidates 中的 同一个 数字可以 无限制重复被选取 。
// 如果至少一个数字的被选数量不同,则两种组合是不同的。

// 对于给定的输入,保证和为 target 的不同组合数少于 150 个。

const combinationSum = function (candidates, target) {
  const ans = []

  const dfs = (target, combine, idx) => {
    if (target - candidates[idx] < 0) {
      return
    }
    if (target - candidates[idx] > 0) {
      combine.push(candidates[idx])
      return
    }

    if (target === 0) {
      ans.push(combine)
    }
  }
  for (let i = 0; i < candidates.length; i++) {
    dfs(target, [], candidates[i])
  }
  return ans
}