diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 31a808b0..5be94996 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -187,7 +187,23 @@ var twoSum = function (nums, target) { }; ``` +php +```php +function twoSum(array $nums, int $target): array +{ + for ($i = 0; $i < count($nums);$i++) { + // 计算剩下的数 + $residue = $target - $nums[$i]; + // 匹配的index,有则返回index, 无则返回false + $match_index = array_search($residue, $nums); + if ($match_index !== false && $match_index != $i) { + return array($i, $match_index); + } + } + return []; +} +``` ----------------------- diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 5b77a170..36abb58c 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -354,6 +354,47 @@ def is_valid(strs) end ``` +php: + +```php +function threeSum(array $nums): array +{ + $result = []; + $length = count($nums); + if ($length < 3) { + return []; + } + sort($nums); + for ($i = 0; $i < $length; $i++) { + // 如果大于0结束 + if ($nums[$i] > 0) break; + // 去重 + if ($i > 0 && $nums[$i] == $nums[$i - 1]) continue; + $left = $i + 1; + $right = $length - 1; + // 比较 + while ($left < $right) { + $sum = $nums[$i] + $nums[$left] + $nums[$right]; + if ($sum < 0) { + $left++; + } elseif ($sum > 0) { + $right--; + } else { + array_push($result, [$nums[$i], $nums[$left], $nums[$right]]); + while ($left < $right && $nums[$left] == $nums[$left + 1]) $left++; + while ($left < $right && $nums[$right - 1] == $nums[$right]) $right--; + $left++; + $right--; + } + } + } + + return $result; +} +``` + + + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index 47cb41af..50e70b3e 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -279,9 +279,7 @@ Python: ```python class Solution: # 动态规划 def uniquePaths(self, m: int, n: int) -> int: - dp = [[0 for i in range(n)] for j in range(m)] - for i in range(m): dp[i][0] = 1 - for j in range(n): dp[0][j] = 1 + dp = [[1 for i in range(n)] for j in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i][j - 1] + dp[i - 1][j] diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 680af587..96899d37 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -283,7 +283,18 @@ func climbStairs(n int) int { return dp[n] } ``` - +Javascript: +```Javascript +var climbStairs = function(n) { + // dp[i] 为第 i 阶楼梯有多少种方法爬到楼顶 + // dp[i] = dp[i - 1] + dp[i - 2] + let dp = [1 , 2] + for(let i = 2; i < n; i++) { + dp[i] = dp[i - 1] + dp[i - 2] + } + return dp[n - 1] +}; +``` ----------------------- diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index e38c5ade..b93d8cd5 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -376,6 +376,28 @@ func isBST(root *TreeNode, min, max int) bool { return isBST(root.Left, min, root.Val) && isBST(root.Right, root.Val, max) } ``` +```go +// 中序遍历解法 +func isValidBST(root *TreeNode) bool { + // 保存上一个指针 + var prev *TreeNode + var travel func(node *TreeNode) bool + travel = func(node *TreeNode) bool { + if node == nil { + return true + } + leftRes := travel(node.Left) + // 当前值小于等于前一个节点的值,返回false + if prev != nil && node.Val <= prev.Val { + return false + } + prev = node + rightRes := travel(node.Right) + return leftRes && rightRes + } + return travel(root) +} +``` JavaScript版本 diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 2b628ec4..bb0d6d34 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -205,6 +205,7 @@ public: Java: ```Java +//DFS递归 class Solution { /** * 前后序遍历都可以 @@ -226,6 +227,31 @@ class Solution { root.right = tmp; } } + +//BFS +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) {return null;} + ArrayDeque deque = new ArrayDeque<>(); + deque.offer(root); + while (!deque.isEmpty()) { + int size = deque.size(); + while (size-- > 0) { + TreeNode node = deque.poll(); + swap(node); + if (node.left != null) {deque.offer(node.left);} + if (node.right != null) {deque.offer(node.right);} + } + } + return root; + } + + public void swap(TreeNode root) { + TreeNode temp = root.left; + root.left = root.right; + root.right = temp; + } +} ``` Python: diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index a893c191..dffc89e6 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -313,63 +313,47 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` - -JavaScript版本 -> 递归 - +JavaScript版本: +1. 使用递归的方法 ```javascript -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ - -/** - * @param {TreeNode} root - * @param {TreeNode} p - * @param {TreeNode} q - * @return {TreeNode} - */ var lowestCommonAncestor = function(root, p, q) { - if(root.val > p.val && root.val > q.val) - return lowestCommonAncestor(root.left, p , q); - else if(root.val < p.val && root.val < q.val) - return lowestCommonAncestor(root.right, p , q); - return root; -}; -``` - -> 迭代 - -```javascript -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ - -/** - * @param {TreeNode} root - * @param {TreeNode} p - * @param {TreeNode} q - * @return {TreeNode} - */ -var lowestCommonAncestor = function(root, p, q) { - while(1) { - if(root.val > p.val && root.val > q.val) - root = root.left; - else if(root.val < p.val && root.val < q.val) - root = root.right; - else - break; + // 使用递归的方法 + // 1. 使用给定的递归函数lowestCommonAncestor + // 2. 确定递归终止条件 + if(root === null) { + return root; + } + if(root.val>p.val&&root.val>q.val) { + // 向左子树查询 + let left = lowestCommonAncestor(root.left,p,q); + return left !== null&&left; + } + if(root.valp.val&&root.val>q.val) { + root = root.left; + }else if(root.val binaryTreePaths(TreeNode root) { + List res = new ArrayList<>(); + helper(root, new StringBuilder(), res); + return res; + } + + public void helper(TreeNode root, StringBuilder sb, List res) { + if (root == null) {return;} + // 遇到叶子结点就放入当前路径到res集合中 + if (root.left == null && root.right ==null) { + sb.append(root.val); + res.add(sb.toString()); + // 记得结束当前方法 + return; + } + helper(root.left,new StringBuilder(sb).append(root.val + "->"),res); + helper(root.right,new StringBuilder(sb).append(root.val + "->"),res); + } +} + +//针对解法二优化,思路本质是一样的 +class Solution { + public List binaryTreePaths(TreeNode root) { + List res = new ArrayList<>(); + helper(root, "", res); + return res; + } + + public void helper(TreeNode root, String path, List res) { + if (root == null) {return;} + // 由原始解法二可以知道,root的值肯定会下面某一个条件加入到path中,那么干脆直接在这一步加入即可 + StringBuilder sb = new StringBuilder(path); + sb.append(root.val); + if (root.left == null && root.right ==null) { + res.add(sb.toString()); + }else{ + // 如果是非叶子结点则还需要跟上一个 “->” + sb.append("->"); + helper(root.left,sb.toString(),res); + helper(root.right,sb.toString(),res); + } + } +} + ``` Python: @@ -350,7 +397,7 @@ class Solution: ``` Go: - + ```go func binaryTreePaths(root *TreeNode) []string { res := make([]string, 0) diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index 60d6d165..d0922de1 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -214,8 +214,26 @@ class Solution: return dp[n] ``` +Python3: +```python +class Solution: + def numSquares(self, n: int) -> int: + # 初始化 + # 组成和的完全平方数的最多个数,就是只用1构成 + # 因此,dp[i] = i + dp = [i for i in range(n + 1)] + # dp[0] = 0 无意义,只是为了方便记录特殊情况: + # n本身就是完全平方数,dp[n] = min(dp[n], dp[n - n] + 1) = 1 + for i in range(1, n): # 遍历物品 + if i * i > n: + break + num = i * i + for j in range(num, n + 1): # 遍历背包 + dp[j] = min(dp[j], dp[j - num] + 1) + return dp[n] +``` Go: ```go diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index cf60575f..7b0dbd0f 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -225,7 +225,20 @@ class Solution: Go: +Javascript: +```Javascript +var integerBreak = function(n) { + let dp = new Array(n + 1).fill(0) + dp[2] = 1 + for(let i = 3; i <= n; i++) { + for(let j = 1; j < i; j++) { + dp[i] = Math.max(dp[i], dp[i - j] * j, (i - j) * j) + } + } + return dp[n] +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 0d306c74..75c665cd 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -240,6 +240,26 @@ class Solution: Go: +javaScript: + +```js +var canPartition = function(nums) { + const sum = (nums.reduce((p, v) => p + v)); + if (sum & 1) return false; + const dp = Array(sum / 2 + 1).fill(0); + for(let i = 0; i < nums.length; i++) { + for(let j = sum / 2; j >= nums[i]; j--) { + dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]); + if (dp[j] === sum / 2) { + return true; + } + } + } + return dp[sum / 2] === sum / 2; +}; +``` + + ----------------------- diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 1831a7a5..66be790f 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -345,6 +345,40 @@ public: Java: +暴力法 +```java +class Solution { + public int[] findMode(FindModeInBinarySearchTree.TreeNode root) { + Map map = new HashMap<>(); + List list = new ArrayList<>(); + if (root == null) return list.stream().mapToInt(Integer::intValue).toArray(); + // 获得频率 Map + searchBST(root, map); + List> mapList = map.entrySet().stream() + .sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue())) + .collect(Collectors.toList()); + list.add(mapList.get(0).getKey()); + // 把频率最高的加入 list + for (int i = 1; i < mapList.size(); i++) { + if (mapList.get(i).getValue() == mapList.get(i - 1).getValue()) { + list.add(mapList.get(i).getKey()); + } else { + break; + } + } + return list.stream().mapToInt(Integer::intValue).toArray(); + } + + void searchBST(FindModeInBinarySearchTree.TreeNode curr, Map map) { + if (curr == null) return; + map.put(curr.val, map.getOrDefault(curr.val, 0) + 1); + searchBST(curr.left, map); + searchBST(curr.right, map); + } + +} +``` + ```Java class Solution { ArrayList resList; @@ -474,7 +508,7 @@ func traversal(root *TreeNode,history map[int]int){ } ``` -计数法BSL(此代码在执行代码里能执行,但提交后报错,不知为何,思路是对的) +计数法,不使用额外空间,利用二叉树性质,中序遍历 ```go /** @@ -485,90 +519,108 @@ func traversal(root *TreeNode,history map[int]int){ * Right *TreeNode * } */ - var count,maxCount int //统计计数 -func findMode(root *TreeNode) []int { - var result []int - var pre *TreeNode //前指针 - if root.Left==nil&&root.Right==nil{ - result=append(result,root.Val) - return result + func findMode(root *TreeNode) []int { + res := make([]int, 0) + count := 1 + max := 1 + var prev *TreeNode + var travel func(node *TreeNode) + travel = func(node *TreeNode) { + if node == nil { + return + } + travel(node.Left) + if prev != nil && prev.Val == node.Val { + count++ + } else { + count = 1 + } + if count >= max { + if count > max && len(res) > 0 { + res = []int{node.Val} + } else { + res = append(res, node.Val) + } + max = count + } + prev = node + travel(node.Right) } - traversal(root,&result,pre) - return result -} -func traversal(root *TreeNode,result *[]int,pre *TreeNode){//遍历统计 - //如果BSL中序遍历相邻的两个节点值相同,则统计频率;如果不相同,依据BSL中序遍历排好序的性质,重新计数 - if pre==nil{ - count=1 - }else if pre.Val==root.Val{ - count++ - }else { - count=1 - } - //如果统计的频率等于最大频率,则加入结果集;如果统计的频率大于最大频率,更新最大频率且重新将结果加入新的结果集中 - if count==maxCount{ - *result=append(*result,root.Val) - }else if count>maxCount{ - maxCount=count//重新赋值maxCount - *result=[]int{}//清空result中的内容 - *result=append(*result,root.Val) - } - pre=root//保存上一个的节点 - if root.Left!=nil{ - traversal(root.Left,result,pre) - } - if root.Right!=nil{ - traversal(root.Right,result,pre) - } + travel(root) + return res } ``` -JavaScript版本 - +JavaScript版本: +使用额外空间map的方法: ```javascript -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[]} - */ -var findMode = function (root) { - let maxCount = 0; - let curCount = 0; - let pre = null; - let res = []; - const inOrder = (root) => { - if (root === null) - return; - inOrder(root.left); - - if (pre === null) - curCount = 1; - else if (pre.val === root.val) - curCount++; - else - curCount = 1; - pre = root; - - if (curCount === maxCount) - res.push(root.val); - - if (curCount > maxCount) { - maxCount = curCount; - res.splice(0, res.length); - res.push(root.val); +var findMode = function(root) { + // 使用递归中序遍历 + let map = new Map(); + // 1. 确定递归函数以及函数参数 + const traverTree = function(root) { + // 2. 确定递归终止条件 + if(root === null) { + return ; } - - inOrder(root.right); - return; + traverTree(root.left); + // 3. 单层递归逻辑 + map.set(root.val,map.has(root.val)?map.get(root.val)+1:1); + traverTree(root.right); } - inOrder(root); + traverTree(root); + //上面把数据都存储到map + //下面开始寻找map里面的 + // 定义一个最大出现次数的初始值为root.val的出现次数 + let maxCount = map.get(root.val); + // 定义一个存放结果的数组res + let res = []; + for(let [key,value] of map) { + // 如果当前值等于最大出现次数就直接在res增加该值 + if(value === maxCount) { + res.push(key); + } + // 如果value的值大于原本的maxCount就清空res的所有值,因为找到了更大的 + if(value>maxCount) { + res = []; + maxCount = value; + res.push(key); + } + } + return res; +}; +``` +不使用额外空间,利用二叉树性质,中序遍历(有序): +```javascript +var findMode = function(root) { + // 不使用额外空间,使用中序遍历,设置出现最大次数初始值为1 + let count = 0,maxCount = 1; + let pre = root,res = []; + // 1.确定递归函数及函数参数 + const travelTree = function(cur) { + // 2. 确定递归终止条件 + if(cur === null) { + return ; + } + travelTree(cur.left); + // 3. 单层递归逻辑 + if(pre.val === cur.val) { + count++; + }else { + count = 1; + } + pre = cur; + if(count === maxCount) { + res.push(cur.val); + } + if(count > maxCount) { + res = []; + maxCount = count; + res.push(cur.val); + } + travelTree(cur.right); + } + travelTree(root); return res; }; ``` diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index cf004b50..dddac899 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -220,7 +220,17 @@ func fib(n int) int { return c } ``` - +Javascript: +```Javascript +var fib = function(n) { + let dp = [0, 1] + for(let i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2] + } + console.log(dp) + return dp[n] +}; +``` diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 8fa756bc..47b2b434 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -255,6 +255,29 @@ func findMIn(root *TreeNode,res *[]int){ findMIn(root.Right,res) } ``` +```go +// 中序遍历的同时计算最小值 +func getMinimumDifference(root *TreeNode) int { + // 保留前一个节点的指针 + var prev *TreeNode + // 定义一个比较大的值 + min := math.MaxInt64 + var travel func(node *TreeNode) + travel = func(node *TreeNode) { + if node == nil { + return + } + travel(node.Left) + if prev != nil && node.Val - prev.Val < min { + min = node.Val - prev.Val + } + prev = node + travel(node.Right) + } + travel(root) + return min +} +``` JavaScript版本 diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 2a88f195..26394eaa 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -315,6 +315,59 @@ func trimBST(root *TreeNode, low int, high int) *TreeNode { ``` +JavaScript版本: +迭代: +```js +var trimBST = function(root, low, high) { + if(root === null) { + return null; + } + while(root !==null &&(root.valhigh)) { + if(root.valhigh) { + cur.right = cur.right.left; + } + cur = cur.right; + } + return root; +}; +``` + +递归: +```js +var trimBST = function (root,low,high) { + if(root === null) { + return null; + } + if(root.valhigh) { + let left = trimBST(root.left,low,high); + return left; + } + root.left = trimBST(root.left,low,high); + root.right = trimBST(root.right,low,high); + return root; + } +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 794e0ae2..61027453 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -271,6 +271,9 @@ class Solution: Go: + +递归法 + ```Go func insertIntoBST(root *TreeNode, val int) *TreeNode { if root == nil { @@ -285,6 +288,31 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode { return root } ``` +迭代法 +```go +func insertIntoBST(root *TreeNode, val int) *TreeNode { + if root == nil { + return &TreeNode{Val:val} + } + node := root + var pnode *TreeNode + for node != nil { + if val > node.Val { + pnode = node + node = node.Right + } else { + pnode = node + node = node.Left + } + } + if val > pnode.Val { + pnode.Right = &TreeNode{Val: val} + } else { + pnode.Left = &TreeNode{Val: val} + } + return root +} +``` JavaScript版本 diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index 55383e91..d4dfe0c6 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -188,6 +188,21 @@ struct TreeNode { Java: +```java +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} +``` + Python: diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index 70c6f015..1701086e 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -118,6 +118,27 @@ class Solution { } ``` +```python +# 方法一:可以使用切片方法 +class Solution: + def reverseLeftWords(self, s: str, n: int) -> str: + return s[n:] + s[0:n] + +# 方法二:也可以使用上文描述的方法,有些面试中不允许使用切片,那就使用上文作者提到的方法 +# class Solution: +# def reverseLeftWords(self, s: str, n: int) -> str: +# s = list(s) +# s[0:n] = list(reversed(s[0:n])) +# s[n:] = list(reversed(s[n:])) +# s.reverse() + +# return "".join(s) + + +# 时间复杂度:O(n) +# 空间复杂度:O(n),python的string为不可变,需要开辟同样大小的list空间来修改 +``` + Go: ```go diff --git a/problems/动态规划-股票问题总结篇.md b/problems/动态规划-股票问题总结篇.md index cac77b65..d22132c0 100644 --- a/problems/动态规划-股票问题总结篇.md +++ b/problems/动态规划-股票问题总结篇.md @@ -381,6 +381,12 @@ dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]); dp[i][2] = dp[i - 1][0] + prices[i]; dp[i][3] = dp[i - 1][2]; ``` +```C++ +dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3]- prices[i], dp[i - 1][1]) - prices[i]; +dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]); +dp[i][2] = dp[i - 1][0] + prices[i]; +dp[i][3] = dp[i - 1][2]; +``` 整体代码如下: diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index 1269d9c1..85bc7e42 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -82,7 +82,7 @@ leetcode上没有纯01背包的问题,都是01背包应用方面的题目, 那么可以有两个方向推出来dp[i][j], -* 由dp[i - 1][j]推出,即背包容量为j,里面不放物品i的最大价值,此时dp[i][j]就是dp[i - 1][j] +* 由dp[i - 1][j]推出,即背包容量为j,里面不放物品i的最大价值,此时dp[i][j]就是dp[i - 1][j]。(其实就是当物品i的重量大于背包j的重量时,物品i无法放进背包中,所以被背包内的价值依然和前面相同。) * 由dp[i - 1][j - weight[i]]推出,dp[i - 1][j - weight[i]] 为背包容量为j - weight[i]的时候不放物品i的最大价值,那么dp[i - 1][j - weight[i]] + value[i] (物品i的价值),就是背包放物品i得到的最大价值 所以递归公式: dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); @@ -380,6 +380,52 @@ func main() { } ``` +javaScript: + +```js +function testWeightBagProblem (wight, value, size) { + const len = wight.length, + dp = Array.from({length: len + 1}).map( + () => Array(size + 1).fill(0) + ); + + for(let i = 1; i <= len; i++) { + for(let j = 0; j <= size; j++) { + if(wight[i - 1] <= j) { + dp[i][j] = Math.max( + dp[i - 1][j], + value[i - 1] + dp[i - 1][j - wight[i - 1]] + ) + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + +// console.table(dp); + + return dp[len][size]; +} + +function testWeightBagProblem2 (wight, value, size) { + const len = wight.length, + dp = Array(size + 1).fill(0); + for(let i = 1; i <= len; i++) { + for(let j = size; j >= wight[i - 1]; j--) { + dp[j] = Math.max(dp[j], value[i - 1] + dp[j - wight[i - 1]]); + } + } + return dp[size]; +} + + +function test () { + console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); +} + +test(); +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index 48275908..36856cd6 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -294,6 +294,29 @@ func main() { } ``` +javaScript: + +```js + +function testWeightBagProblem(wight, value, size) { + const len = wight.length, + dp = Array(size + 1).fill(0); + for(let i = 1; i <= len; i++) { + for(let j = size; j >= wight[i - 1]; j--) { + dp[j] = Math.max(dp[j], value[i - 1] + dp[j - wight[i - 1]]); + } + } + return dp[size]; +} + + +function test () { + console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); +} + +test(); +``` + -----------------------