# 【Leetcode 做题学算法周刊】第六期

mcchen

• 题目分析设想
• 编写代码验证
• 查阅他人解法
• 思考总结

## Easy

### 110.平衡二叉树

#### 题目描述

``````    3
/ \
9  20
/  \
15   7``````

``````       1
/ \
2   2
/ \
3   3
/ \
4   4``````

#### 编写代码验证

Ⅰ.计算子树最大深度做判断

``````/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
if (root === null) return true
function maxDepth (node) {
if (node === null) return 0
const l = maxDepth(node.left)
const r = maxDepth(node.right)
return Math.max(l, r) + 1
}

return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1
&& isBalanced(root.left)
&& isBalanced(root.right)
};``````

• 227/227 cases passed (80 ms)
• Your runtime beats 77.66 % of javascript submissions
• Your memory usage beats 26.73 % of javascript submissions (37.8 MB)
• 时间复杂度 `O(n^2)`

Ⅱ.自底而上

``````/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
function maxDepth (node) {
if (node === null) return 0
const l = maxDepth(node.left)
if (l === -1) return -1
const r = maxDepth(node.right)
if (r === -1) return -1
return Math.abs(l - r) <= 1 ? Math.max(l, r) + 1 : -1
}

return maxDepth(root) !== -1
};``````

• 227/227 cases passed (72 ms)
• Your runtime beats 95.44 % of javascript submissions
• Your memory usage beats 50.5 % of javascript submissions (37.5 MB)
• 时间复杂度 `O(n)`

### 111.二叉树的最小深度

#### 题目描述

``````    3
/ \
9  20
/  \
15   7``````

#### 编写代码验证

Ⅰ.递归

``````/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (root === null) return 0
if (root.left === null && root.right === null) return 1
let res = Infinity
if(root.left !== null) {
res = Math.min(minDepth(root.left), res)
}
if(root.right !== null) {
res = Math.min(minDepth(root.right), res)
}
return res + 1
};``````

• 41/41 cases passed (76 ms)
• Your runtime beats 69.08 % of javascript submissions
• Your memory usage beats 5.55 % of javascript submissions (37.9 MB)
• 时间复杂度 `O(n)`

Ⅱ.利用栈迭代

``````/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (root === null) return 0
if (root.left === null && root.right === null) return 1
// 栈
let s = [{
node: root,
dep: 1
}]
let dep = Infinity
while(s.length) {
// 先进后出
var cur = s.pop()
if (cur.node !== null) {
let curDep = cur.dep
if (cur.node.left === null && cur.node.right === null) {
dep = Math.min(dep, curDep)
}
if (cur.node.left !== null) s.push({node: cur.node.left, dep: curDep + 1})
if (cur.node.right !== null) s.push({node: cur.node.right, dep: curDep + 1})
}
}
return dep
};``````

• 41/41 cases passed (68 ms)
• Your runtime beats 93.82 % of javascript submissions
• Your memory usage beats 75.31 % of javascript submissions (37 MB)
• 时间复杂度 `O(n)`

Ⅲ.利用队列

``````/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (root === null) return 0
if (root.left === null && root.right === null) return 1
// 队列
let s = [{
node: root,
dep: 1
}]
let dep = 0
while(s.length) {
// 先进先出
var cur = s.shift()
var node = cur.node
dep = cur.dep
if (node.left === null && node.right === null) break;
if (node.left !== null) s.push({node: node.left, dep: dep + 1})
if (node.right !== null) s.push({node: node.right, dep: dep + 1})
}
return dep
};``````

• 41/41 cases passed (76 ms)
• Your runtime beats 69.08 % of javascript submissions
• Your memory usage beats 6.79 % of javascript submissions (37.7 MB)
• 时间复杂度 `O(n)`

### 112.路径总和

#### 题目描述

``````              5
/ \
4   8
/   / \
11  13  4
/  \      \
7    2      1``````

• 递归
• 利用栈迭代

#### 编写代码验证

Ⅰ.递归

``````/**
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
var hasPathSum = function(root, sum) {
if (root === null) return false
// 剩余需要的值
sum -= root.val
if (root.left === null && root.right === null) {
return sum === 0
} else {
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum)
}
};``````

• 114/114 cases passed (80 ms)
• Your runtime beats 62.09 % of javascript submissions
• Your memory usage beats 56.9 % of javascript submissions (37.1 MB)
• 时间复杂度 `O(n)`

Ⅱ.迭代

``````/**
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
var hasPathSum = function(root, sum) {
if (root === null) return false
// 栈
let stack = [{
node: root,
remain: sum - root.val
}]
while(stack.length) {
// 先进后出
var cur = stack.pop()
var node = cur.node
if (node.left === null && node.right === null && cur.remain === 0) return true
if (node.left !== null) {
stack.push({
node: node.left,
remain: cur.remain - node.left.val
})
}
if (node.right !== null) {
stack.push({
node: node.right,
remain: cur.remain - node.right.val
})
}
}
return false
};``````

• 114/114 cases passed (72 ms)
• Your runtime beats 88.51 % of javascript submissions
• Your memory usage beats 33.33 % of javascript submissions (37.2 MB)
• 时间复杂度 `O(n)`

#### 查阅他人解法

Ⅰ.利用队列

``````/**
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
var hasPathSum = function(root, sum) {
if (root === null) return false
// 队列
let q = [{
node: root,
sum: root.val
}]
while(q.length) {
// 当前层元素的个数
for(let i = 0; i < q.length; i++) {
let cur = q.shift()
let node = cur.node
if (node.left === null && node.right === null && cur.sum === sum) return true

if (node.left !== null) {
q.push({ node: node.left, sum: cur.sum + node.left.val})
}
if (node.right !== null) {
q.push({ node: node.right, sum: cur.sum + node.right.val})
}
}
}
return false
};``````

• 114/114 cases passed (72 ms)
• Your runtime beats 88.51 % of javascript submissions
• Your memory usage beats 56.32 % of javascript submissions (37.1 MB)
• 时间复杂度 `O(n)`

### 118.杨辉三角

#### 题目描述

``````输入: 5

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]``````

#### 编写代码验证

Ⅰ.动态规划

``````/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
let res = []
for(let i = 0; i < numRows; i++) {
// 所有默认都填了1，可以节省不少运算
res.push(new Array(i+1).fill(1))
// 第三行开始才需要修改
for(j = 1; j < i; j++) {
res[i][j] = res[i-1][j] + res[i-1][j-1]
}
}
return res
};``````

• 15/15 cases passed (60 ms)
• Your runtime beats 85.2 % of javascript submissions
• Your memory usage beats 55.52 % of javascript submissions (33.6 MB)
• 时间复杂度 `O(n^2)`

#### 查阅他人解法

Ⅰ.递归

``````/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function (numRows) {
let res = []

function sub(row, numRows, arr) {
let temp = []
if (row < numRows) {
for (let i = 0; i <= row; i++) {
if (row === 0) {
temp.push(1)
} else {
let left = i - 1 >= 0 ? arr[row - 1][i - 1] : 0
let right = i < arr[row - 1].length ? arr[row - 1][i] : 0
temp.push(left + right)
}
}
arr.push(temp)
sub(++row, numRows, arr)
return arr
} else {
return arr
}
}
return sub(0, numRows, res)
};``````

• 15/15 cases passed (64 ms)
• Your runtime beats 68.27 % of javascript submissions
• Your memory usage beats 56.86 % of javascript submissions (33.6 MB)
• 时间复杂度 `O(n^2)`

Ⅱ.二项式定理

``````/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
var res = [];

/**
* 组合数
* @param n
* @param r
* @returns {number}
* @constructor
*/
function C(n, r) {
if(n == 0) return 1;
return F(n) / F(r) / F(n - r);
}
/**
* 阶乘
* @param n
* @returns {number}
* @constructor
*/
function F(n) {
var s = 1;
for(var i = 1;i <= n;i++) {
s *= i;
}
return s;
}

for (var i = 0;i < numRows;i++){
res[i] = [];
for (var j = 0;j < i + 1;j++){
res[i].push(C(i, j));
}
}
return res;
};``````

• 15/15 cases passed (64 ms)
• Your runtime beats 68.27 % of javascript submissions
• Your memory usage beats 5.02 % of javascript submissions (34.3 MB)
• 时间复杂度 `O(n^2)`

### 119.杨辉三角Ⅱ

#### 题目描述

``````输入: 3

#### 编写代码验证

Ⅰ.动态规划

``````/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
// rowIndex 是索引，0相当于第1行
if (rowIndex === 0) return [1]
let res = []
for(let i = 0; i < rowIndex + 1; i++) {
let temp = new Array(i+1).fill(1)
// 第三行开始才需要修改
for(let j = 1; j < i; j++) {
temp[j] = res[j - 1] + res[j]
}
res = temp
}
return res
};``````

• 34/34 cases passed (64 ms)
• Your runtime beats 75.77 % of javascript submissions
• Your memory usage beats 54.9 % of javascript submissions (33.8 MB)
• 时间复杂度 `O(n^2)`

Ⅱ.二项式定理

``````/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
/**
* 组合数
* @param n
* @param r
* @returns {number}
* @constructor
*/
function C(n, r) {
if(n == 0) return 1;
return F(n) / F(r) / F(n - r);
}
/**
* 阶乘
* @param n
* @returns {number}
* @constructor
*/
function F(n) {
var s = 1;
for(var i = 1;i <= n;i++) {
s *= i;
}
return s;
}
let res = []
// 因为是通过上一项计算，所以第1项的 n 为0
for (var i = 0;i < rowIndex + 1;i++){
res.push(C(rowIndex, i));
}
return res;
};``````

• 34/34 cases passed (52 ms)
• Your runtime beats 99.12 % of javascript submissions
• Your memory usage beats 41.18 % of javascript submissions (34.5 MB)
• 时间复杂度 `O(n)`

#### 查阅他人解法

Ⅰ.反转复制

``````/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
// rowIndex 是索引，0相当于第1行
if (rowIndex === 0) return [1]
let res = []
for(let i = 0; i < rowIndex + 1; i++) {
let temp = new Array(i+1).fill(1)
// 第三行开始才需要修改
const mid = i >>> 1
for(let j = 1; j < i; j++) {
if (j > mid) {
temp[j] = temp[i - j]
} else {
temp[j] = res[j - 1] + res[j]
}
}
res = temp
}
return res
};``````

• 34/34 cases passed (60 ms)
• Your runtime beats 88.47 % of javascript submissions
• Your memory usage beats 60.78 % of javascript submissions (33.7 MB)
• 时间复杂度 `O(n^2)`

#### 思考总结

（完）

(转载请注明出处：https://chenjiahao.xyz)

492 声望
16 粉丝