对称二叉树
// 给你一个二叉树的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++) {
while (stack[stack.length - 1].index != -1 && stack[stack.length - 1].height > heights[i]) {
let pop = stack.pop()
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 = Math.max(max, (right - stack[stack.length - 1].index) * pop.height)
}
return max
};
组合总数
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
}