// 求第n个斐波拉契数列之和
function fibonacciSum(n) {
if (n <= 0) {
return false
}
if (n <= 2) {
return 1
}
let pre = prepre = 1
let current = pre + prere
for (let i = 3; i <= n; i++) {
current = pre + prepre
prepre = pre
pre = current
}
return current
}
// 求第n个斐波拉契数列的数,最小空间复杂度
function fibonacci(n) {
if (n <= 0) {
return false
}
if (n <= 2) {
return 1
}
let i = 3
let list = [1, 1]
while(i <= n) {
[list[0], list[1]] = [list[1], list[0] + list[1]]
i++
}
return list[1]
}
// 每次爬1或2步,求爬n步有多少种方法
function climbStairs(n) {
if (n === 1 || n === 2) {
return n
}
let dp_n_1 = 1
let dp_n_2 = 2
let current = dp_n_1 + dp_n_2
let i = 3
while(i <= n) {
current = dp_n_1 + dp_n_2
dp_n_1 = dp_n_2
dp_n_2 = current
i ++
}
return current
}
// 最小路径和
function minPathSum(arr) {
for (let i = 0; i < arr.length; i ++) {
for (let j = 0; j < arr[0].length; j++) {
if (i !== 0 && j !== 0) {
arr[i][j] += Math.min(arr[i - 1][j], arr[i][j - 1])
} else if (i === 0 && j !== 0) {
arr[i][j] += arr[i][j - 1]
} else if (i !== 0 && j === 0) {
arr[i][j] += arr[i - 1][j]
}
}
}
return arr[arr.length - 1][arr[0].length - 1]
}
常见算法题
最新推荐文章于 2022-07-30 12:53:47 发布