一、路径总和 I 递归 public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { return root.val == sum; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);}...
搜索二维矩阵问题 前言 搜索二维矩阵 I和搜索二维矩阵 II两道题在解题思路上都是围绕二分查找展开的,搜索二维矩阵 I比较简单,纯暴力或直接套二分查找的公式(二维的二分查找)即可,而搜索二维矩阵 II的解题方法就比较特别,个人感觉有点意思,故在此记录下~...
一、零钱兑换 I 自顶向下、使用备忘录(HashMap)的递归解法 // 备忘录Map<Integer, Integer> memoMap = new HashMap<>();public int coinChange(int[] coins, int amount) { // 查备忘录,避免重复计算 if (memoMap.containsKey(amount)) { return memoMap.get(amount); } // base case if (amount == 0) return 0; // 下面的递归入参,假如 amount - coin < 0,则返回 -1 if (amount < 0) return -1; // 最差的情况,就是使用 amount 个面值为 1 的硬币,而 amount + 1 就是个不存在的值,下面要比较最小值,则每次递归都使用 amount + 1 比较求最小值即可 int res = amount + 1; for (int coin : coins) { // 子问题(目标金额减去当前 coin) int subProblem = coinChange(coins, amount - coin); if (subProblem == -1) continue; // 求最值,即 res 与 子问题加上一个 coin(与上面`目标金额减去当前 coin`相对应,即自顶向下的思想) 求最值 res = Math.min(res, subProblem + 1); } res = res == amount + 1 ? -1 : res; memoMap.put(amount, res); return res;}...
本文整理于自己的学习笔记.. 一、打家劫舍 I 自顶向下、使用备忘录的递归解法 自顶向下:递归一般是自顶向下,依赖于子问题优化函数的结果,只有子问题完全求出,也就是子问题的递归返回结果,原问题才能求解。...