每日一题 -- 树
865.具有所有最深节点的最小子树
865.具有所有最深节点的最小子树
var subtreeWithAllDeepest = function (root) {
const dfs = (root, depth) => {
if (!root) return [root, depth]
const [ln, ld] = dfs(root.left, depth + 1)
const [rn, rd] = dfs(root.right, depth + 1)
if (ld === rd) return [root, ld]
if (ld < rd) return [rn, rd]
if (ld > rd) return [ln,ld]
}
return dfs(root, -1)[0]
};
91算法 -- 背包问题
416. 分割等和子集
416. 分割等和子集
想说的话
- 这题做了 1h 多了,一开始是按照背包来写的,但是想不出来,然后就想用回溯来做,然后超时了,有太多重复的情况了,最后没做出来,暂时就这样吧,明天抽时间看看题解再搞,下一部分学习咯
var canPartition = function (nums) {
const rest = nums.reduce((pre, cur) => pre + cur, 0)
if (rest % 2) return false
const target = rest >>> 1
let res = false
const dfs = (index, total) => {
if (total > target || index === nums.length) return
if (total === target) {
res = true
return
}
dfs(index + 1, total + nums[index])
dfs(index + 1, total)
}
dfs(0, 0)
return res
};
var canPartition = function (nums) {
let res = false
const dfs = (index, left, right) => {
if (index === nums.length) {
if (left === right) {
res = true
return
}
return
}
dfs(index + 1, left + nums[index], right)
dfs(index + 1, left, right + nums[index])
}
dfs(0, 0, 0)
return res
};
var canPartition = function (nums) {
const rest = nums.reduce((pre, cur) => pre + cur, 0)
if (rest % 2) return false
const target = rest >>> 1
let res = false
const len = nums.length
let dp = new Array(len)
dp[0] = [0, nums[0]]
for (let i = 1; i < len; i++) {
console.log(dp,dp[i-1].map(i=>i),i)
dp[i] = [...dp[i-1],...dp[i-1].map(item => {
if (item+nums[i] === target) {
res = true;
} else if (item+nums[i] < target) {
return item+nums[i]
}else{
return item
}
})]
}
return res
}