前端就该用 JS 刷算法12

114 阅读1分钟

每日一题 -- 树

求和路径

求和路径

// https://leetcode-cn.com/problems/paths-with-sum-lcci/

/**
 * 双递归
 * @分析
 * 1. 求所有路径,不限制根节点开始,叶子节点结束
 * 2. 但是必须是向下
 * 
 * @双递归拆解
 * 1. 第一个递归是:从 root 节点开始,符合条件的数组
 * 2. 第二个递归是:从 当前节点开始,执行第一个递归
 * 
 * @踩的坑
 * 1. 不能左右节点直接走,然后判空,这样会有重复数组出现
 * 2. 树的值可能为负数,所以不能判断 rest<0 就 return
 * 3. 即使 rest === 0,但是只要没到根节点,就有可能还有其他的数组也成立
 * 4. 一开始以为是要将所有值都来一遍,所以存的所有符合要求的 数组
 * 
 */

var pathSum = function(root, sum) {
    const res = []
    const innerDfs = (root,rest,arr) => {
        const temp = rest-root.val
        if(temp === 0) {
            res.push([...arr,root.val])
        }
        if(!root.left && !root.right) return 
       if(root.left) innerDfs(root.left,temp,[...arr,root.val])
       if(root.right)  innerDfs(root.right,temp,[...arr,root.val])
    }
    const outDfs = (root) => {
        if(!root) return 
        innerDfs(root,sum,[])
        outDfs(root.left)
        outDfs(root.right)
    }
    outDfs(root)
    return res.length
};

/**
 * 这里直接存 total 数字
 */
var pathSum = function(root, sum) {
    const total = 0
    const innerDfs = (root,rest) => {
        const temp = rest-root.val
        if(temp === 0) {
            total++
        }
        if(!root.left && !root.right) return 
       if(root.left) innerDfs(root.left,temp)
       if(root.right)  innerDfs(root.right,temp)
    }
    const outDfs = (root) => {
        if(!root) return 
        innerDfs(root,sum)
        outDfs(root.left)
        outDfs(root.right)
    }
    outDfs(root)
    return res.length
};

91算法 -- 位运算

0~n-1中缺失的数字

0~n-1中缺失的数字

// https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof/

/**
 * 0~n-1中缺失的数字
 * @分析
 * 使用异或 ^
 */
var missingNumber = function(nums) {
    let res= nums.length
    nums.forEach((item,index) => {
        res^=item^index
    })
    return res
};