前端就该用 JS 刷算法25(待补)

121 阅读1分钟

每日一题 -- 树

437. 路径总和 III

437. 路径总和 III

// https://leetcode-cn.com/problems/path-sum-iii/
// 437. 路径总和 III


/**
 * @分析
 * 1. 只能从父节点到子节点 -- 和题17是一样的
 * 2. 使用双遍历,一个遍历 dfs 找出以 root 为起点的所有匹配的路径
 * 3. 一个遍历 recursion 自顶向下修改 dfs 的 root 值
 * 
 * @注意
 * 1. 由于根节点可能为负,且求的是全部值,所以在 dfs 中,只有在叶子结点时才会 return 结束
 */
var pathSum = function(root, sum) {
    let res = 0
    // 从某个 root 节点开始,找出合乎规则的路径
    const dfs = (root,leave) => {
        if(root.val === leave){
            res+=1
        }
        if(!root.left && !root.right){
            // 到达叶子节点了,结束
            return
        }
        if(root.left) dfs(root.left,leave-root.val)
        if(root.right) dfs(root.right,leave-root.val)
    }
    // 自顶向下遍历树
    const recuirsion = root => {
        if(!root) return 
        dfs(root,sum)
        recuirsion(root.left,sum)
        recuirsion(root.right,sum)
    }
    recuirsion(root)
    return res
};

91算法 -- 背包问题

322. 零钱兑换

322. 零钱兑换

分析

  • 没有分析,没做出来,所以需要下次补
// https://leetcode-cn.com/problems/coin-change/
// 322. 零钱兑换

/**
 * @分析
 * 1. 遍历除所有情况的时候,会超出时间限制,所以需要优化一下
 * 2. 每次都尽量将最大的取完,然后再进行递归
 */
var coinChange = function (coins, amount) {
    let min = Infinity
    coins = coins.sort((a, b) => b - a)
    const recursion = (leave, times) => {
        if (leave < 0) return
        if (leave === 0) {
            min = Math.min(min, times)
            return
        }
        if(index < coins.length) return 

        for(let coin of  coins) {
            const temp = Math.floor(leave / coins[index])
            leave = leave % coins[index]
            recursion(leave, times+temp)
            recursion
        }

     
        console.log(leave, times, index,temp)
    }
    recursion(amount, 0, 0)
    return min === Infinity ? -1 : min
};